JAXP/XPath example - III
30 June 2008Do 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()); }
Related Posts:
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