Java tutorial
//package com.java2s; 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 { /** * Select node list what matches given xpath query * * @param doc xml document * @param expression xpath query * @return nodes which confirms given xpath query. * @throws XPathExpressionException in case of any errors. */ public static NodeList query(final Document doc, final String expression) throws XPathExpressionException { final XPath xpath = XPathFactory.newInstance().newXPath(); return (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET); } /** * Select node list what matches given xpath query * * @param node xml node * @param expression xpath query * @return nodes which confirms given xpath query. * @throws XPathExpressionException in case of any errors. */ public static NodeList query(final Node node, final String expression) throws XPathExpressionException { final XPath xpath = XPathFactory.newInstance().newXPath(); return (NodeList) xpath.evaluate(expression, node, XPathConstants.NODESET); } }