CODEFETCH™
            Examples
Cache of Javanut5Examples/Chapter5/XPathEvaluator.java from
http://examples.oreilly.com/javanut5/Javanut5Examples.tar.gz
Source code below from:
Java In A Nutshell, 5th Edition
By David Flanagan
Published 15 March, 2005
Average rating

      Powells     Alibris


import javax.xml.xpath.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class XPathEvaluator {
    public static void main(String[] args)
    throws ParserConfigurationException, XPathExpressionException,
           org.xml.sax.SAXException, java.io.IOException
    {
    String documentName = args[0];
    String expression = args[1];

    // Parse the document to a DOM tree
    // XPath can also be used with a SAX InputSource
    DocumentBuilder parser =
        DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = parser.parse(new java.io.File(documentName));
    
    // Get an XPath object to evaluate the expression
    XPath xpath = XPathFactory.newInstance().newXPath();

    System.out.println(xpath.evaluate(expression, doc));

    // Or evaluate the expression to obtain a DOM NodeList of all matching
    // nodes.  Then loop through each of the resulting nodes
    NodeList nodes = (NodeList)xpath.evaluate(expression, doc,
                          XPathConstants.NODESET);
    for(int i = 0, n = nodes.getLength(); i < n; i++) {
        Node node = nodes.item(i);
        System.out.println(node);
    }
    }
}