Java 5 introduces the javax.xml.xpath package, an XML object-model independent library for querying documents with XPath. Java 5 introduced the javax.xml.xpath package to provide an engine and object-model independent XPath library. This package is also available in Java 1.3 and later if you install Java API for XML Processing (JAXP) 1.3 separately. Among other products, Xalan 2.7 and Saxon 8 include an implementation of this library.
Example :
//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.
No comments:
Post a Comment