Thursday 3 March 2011

Java XPath API

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:

No comments:

Post a Comment