Java tutorial
//package com.java2s; //License from project: Open Source License import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Performs a xpath query on a document and returns the matching nodelist. * * @param doc * @param xpathQuery * @return nodelist of matches * @throws Exception */ public static NodeList query(Document doc, String xpathQuery) throws Exception { NodeList result = null; // prepare XPath XPath xpath = XPathFactory.newInstance().newXPath(); try { // query xml result = (NodeList) xpath.evaluate(xpathQuery, doc, XPathConstants.NODESET); } catch (XPathExpressionException xpx) { throw new Exception("Error evaluating XPath: " + xpx.getMessage(), xpx); } return result; } /** * Performs a xpath query on a document and returns the matching nodelist. * * @param context the Context where to start with the query * @param query the XPath-Query * @return nodelist of matches * @throws Exception on error */ public static NodeList query(Node context, String query) throws Exception { NodeList result = null; XPath xpath = XPathFactory.newInstance().newXPath(); try { result = (NodeList) xpath.evaluate(query, context, XPathConstants.NODESET); } catch (XPathExpressionException xpx) { throw new Exception("Error evaluating XPath: " + xpx.getMessage(), xpx); } return result; } }