Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class Main { private static final Map<String, XPathExpression> compiledExpressionCache = new HashMap<String, XPathExpression>(); private static final XPath xpath = XPathFactory.newInstance().newXPath(); /** * Checks in under a given root element whether it can find a child elements * which match the XPath expression supplied. Returns a {@link List} of * {@link Element} if they exist. * * Please note that the XPath parser used is NOT namespace aware. So if you * want to find a element <beans><sec:http> you need to use the following * XPath expression '/beans/http'. * * @param xPathExpression the xPathExpression * @param root the parent DOM element * @return a {@link List} of type {@link Element} if discovered, otherwise an empty list (never null) */ public static List<Element> findElements(String xPathExpression, Element root) { List<Element> elements = new ArrayList<Element>(); NodeList nodes = null; try { XPathExpression expr = compiledExpressionCache.get(xPathExpression); if (expr == null) { expr = xpath.compile(xPathExpression); compiledExpressionCache.put(xPathExpression, expr); } nodes = (NodeList) expr.evaluate(root, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate xpath expression", e); } for (int i = 0, n = nodes.getLength(); i < n; i++) { elements.add((Element) nodes.item(i)); } return elements; } }