Java tutorial
//package com.java2s; import java.util.HashMap; 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.Node; public class Main { private static final Map<String, XPathExpression> COMPILED_EXPRESSION_CACHE = new HashMap<String, XPathExpression>(); private static final XPath XPATH = XPathFactory.newInstance().newXPath(); /** * Checks for a given element whether it can find an attribute which matches * the XPath expression supplied. Returns {@link Node} if exists. * * @param xPathExpression the xPathExpression (required) * @param element (required) * @return the Node if discovered (null if not found) */ public static Node findFirstAttribute(final String xPathExpression, final Element element) { Node attr = null; try { XPathExpression expr = COMPILED_EXPRESSION_CACHE.get(xPathExpression); if (expr == null) { expr = XPATH.compile(xPathExpression); COMPILED_EXPRESSION_CACHE.put(xPathExpression, expr); } attr = (Node) expr.evaluate(element, XPathConstants.NODE); } catch (final XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate xpath expression", e); } return attr; } }