JAXP/XPath example - III

30 June 2008

Do read the first 2 parts of this post before this one. So far, we have seen JAXP and DOM stuff.

Next step is to create an XPathFactory:

XPathFactory factory = XPathFactory.newInstance();

Now we have to use this factory to create an XPath object:

XPath xpath = factory.newXPath();

The XPath object compiles the XPath expression:

XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']/title/text()");

Finally, we will evaluate the XPath expression to get the result using evaluate(…) method.

Object result = expr.evaluate(doc, XPathConstants.NODESET);

Noe you can cast the result to a DOM NodeList and iterate through that to find all the titles as shown below:

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

del.icio.us:JAXP/XPath example - III  digg:JAXP/XPath example - III  spurl:JAXP/XPath example - III  wists:JAXP/XPath example - III  simpy:JAXP/XPath example - III  newsvine:JAXP/XPath example - III  blinklist:JAXP/XPath example - III  furl:JAXP/XPath example - III  reddit:JAXP/XPath example - III  fark:JAXP/XPath example - III  blogmarks:JAXP/XPath example - III  Y!:JAXP/XPath example - III  smarking:JAXP/XPath example - III  magnolia:JAXP/XPath example - III  segnalo:JAXP/XPath example - III  gifttagging:JAXP/XPath example - III

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: JAXP/XPath example - III

Leave a Reply