Java Reference
In-Depth Information
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("contacts.xml");
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
xp.setNamespaceContext(new NSContext());
xp.setXPathFunctionResolver(new DateResolver());
XPathExpression xpe;
String expr;
expr
=
"//tt:contact[tt:date(tt:birth)>tt:date('1960-01-01')]"+
"/tt:name/text()";
xpe = xp.compile(expr);
Object result = xpe.evaluate(doc, XPathConstants.NODESET);
NodeList nl = (NodeList) result;
for (int i = 0; i < nl.getLength(); i++)
System.out.println(nl.item(i).getNodeValue());
Variables and Variable Resolvers
All the previously specified XPath expressions have been based on literal text. XPath
alsoletsyouspecifyvariablestoparameterizetheseexpressions,inasimilarmannerto
using variables with SQL prepared statements.
A variable appears in an expression by prefixing its name (which may or may not
haveanamespaceprefix)witha $ .Forexample, /a/b[@c=$d]/text() isanXPath
expression that selects all a elements of the root node, and all of a 's b elements that
have c attributescontainingthevalueidentifiedbyvariable $d ,andreturnsthetextof
these b elements. This expression corresponds to Listing 10-27 's XML document.
Listing 10-27. A simple XML document for demonstrating an XPath variable
<?xml version="1.0"?>
<a>
<b c="x">b1</b>
<b>b2</b>
<b c="y">b3</b>
<b>b4</b>
<b c="x">b5</b>
</a>
Search WWH ::




Custom Search