A following code snippet shows how easy it is to use the new API.
//Parse document.
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("books.xml");
//Build XPath expression.
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr
= xpath.compile("//book[author='Neal Stephenson']/title/text()");
// Make the query
Object result = expr.evaluate(doc, XPathConstants.NODESET);
//Print results
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
} This example is taken from Elliotte Rusty Harold's article on developerworks titled "The Java XPath API" (I added a few comments).The following is a list of resources for learning XPath and the Java XPath API:- Get started with XPath 2.0 by BenoƮt Marchal (developerWorks, May 2006):Learn how to easily write more sophisticated requests with the new data model, with XPath 2.0.
- Working with JAXP namespace contexts
- XML in a Nutshell (Elliotte Rusty Harold and W. Scott Means, O'Reilly, 2005)
- developerWorks Java technology zone: Explore hundreds of articles about every aspect of Java programming.
- XML:developerWorks XML Zone for technical articles and tips, tutorials, standards, and IBM Redbooks.
{ 0 comments... Views All / Send Comment! }
Post a Comment