Here's a very simple implementation of javax.xml.xpath.XPathVariableResolver
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPathVariableResolver;
public class SimpleVariableResolver implements XPathVariableResolver {
private static final Map<QName, Object> vars =
new HashMap<QName, Object>();
public void addVariable(QName name, Object value) {
vars.put(name, value);
}
public Object resolveVariable(QName name) {
return vars.get(name);
}
}
Use it like this:
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("workbook.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
SimpleVariableResolver resolver = new SimpleVariableResolver();
resolver.addVariable(new QName(null, "id"), 2);
xpath.setXPathVariableResolver(resolver);
XPathExpression expr = xpath.compile("/root/element[@id=$id]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getTextContent());
}
}
On this document:
<root>
<element id="1">one</element>
<element id="2">two</element>
<element id="3">three</element>
</root>
Output:
two