Java Reference
In-Depth Information
To specify variables whose values are obtained during expression evaluation, you
mustregisteravariableresolverwithyour XPath object.A variable resolver isanin-
stanceofaclassthatimplementsthe XPathVariableResolver interfaceinterms
ofits Object resolveVariable(QName variableName) method,andwhich
tells the evaluator about the variable (or variables).
The variableName parameter contains the qualified name of the variable's
name—rememberthatavariablenamemaybeprefixedwithanamespaceprefix.This
method verifies that the qualified name appropriately names the variable and then re-
turns its value.
Aftercreatingthevariableresolver,youregisteritwiththe XPath instancebycalling
XPath 's void setXPathVariableResolver(XPathVariableResolver
resolver) method.
Thefollowingexampledemonstratesallthesetaskstospecify $d inXPathexpression
/a/b[@c=$d]/text() , which returns b1 followed by b5 . It assumes that Listing
10-27 is stored in a file named example.xml :
DocumentBuilderFactory
dbf
=
DocumentBuilderFact-
ory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("example.xml");
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
XPathVariableResolver xpvr;
xpvr = new XPathVariableResolver()
{
@Override
public Object resolveVariable(QName varname)
{
if (varname.getLocalPart().equals("d"))
return "x";
else
return null;
}
};
xp.setXPathVariableResolver(xpvr);
XPathExpression xpe;
xpe = xp.compile("/a/b[@c=$d]/text()");
Search WWH ::




Custom Search