View RSS Feed

My Java Tips

JAXP/XPath example

Rate this Entry
by , 11-03-2011 at 11:50 AM (5406 Views)
I will present an example that will search a XML file and then prints out the titles of all the books it finds.


I will use following books.xml in the example.


<inventory>
<book year="2000">

<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553380958</isbn>
<price>14.95</price>
</book>

<book year="2005">

<author>Larry Niven</author>
<author>Jerry Pournelle</author>
<publisher>Pocket</publisher>
<isbn>0743416910</isbn>
<price>5.99</price>
</book>

<book year="1995">

<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553573862</isbn>
<price>7.50</price>
</book>

<!-- more books... -->

</inventory>
The XPath query that finds all the books is very simple and easy:

//book[author="Neal Stephenson"].

To find the titles of those books written by Neal Stephenson, the expression becomes //book[author="Neal Stephenson"]/title.

We actually want the text node children of the title element. The required full expression well be:

//book[author="Neal Stephenson"]/title/text().

Now I will show how to parse a document using JAXP.


I will present an example that will search a XML file and then prints out the titles of all the books it finds.
First step is to load the document into a DOM Document object. I will use books.xml file in the example and it is assumed that it resides in the current directory:

Here's a simple code fragment that parses the document and constructs the corresponding Document object:

Java Code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("books.xml");
So far, we have seen JAXP and DOM stuff.

Next step is to create an XPathFactory:

Java Code:
XPathFactory factory = XPathFactory.newInstance();
Now we have to use this factory to create an XPath object:

Java Code:
XPath xpath = factory.newXPath();
The XPath object compiles the XPath expression:

Java Code:
XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']/title/text()");
Finally, we will evaluate the XPath expression to get the result using evaluate(...) method.

Java Code:
Object result = expr.evaluate(doc, XPathConstants.NODESET);
Now you can cast the result to a DOM NodeList and iterate through that to find all the titles as shown below:

Java Code:
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getNodeValue());
}

Submit "JAXP/XPath example" to Facebook Submit "JAXP/XPath example" to Digg Submit "JAXP/XPath example" to del.icio.us Submit "JAXP/XPath example" to StumbleUpon Submit "JAXP/XPath example" to Google

Tags: None Add / Edit Tags
Categories
XML

Comments