View RSS Feed

My Java Tips

JAXP/XPath example

Rate this Entry
by , 11-03-2011 at 12:50 PM (7946 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.

<book year="2000">

<author>Neal Stephenson</author>

<book year="2005">

<author>Larry Niven</author>
<author>Jerry Pournelle</author>

<book year="1995">

<author>Neal Stephenson</author>

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

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++) {

Submit "JAXP/XPath example" to Facebook Submit "JAXP/XPath example" to Digg Submit "JAXP/XPath example" to Submit "JAXP/XPath example" to StumbleUpon Submit "JAXP/XPath example" to Google

Tags: None Add / Edit Tags