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);
}
}
}
|