Java Reference
In-Depth Information
Note
The XPath API maps XPath's Boolean, number, string, and nodeset types
to Java's
java.lang.Boolean
,
java.lang.Double
,
String
, and
org.w3c.dom.NodeList
types, respectively. When calling an
evaluate()
method, you specify XPath types via
XPathConstants
constants (
BOOLEAN
,
NUMBER
,
STRING
,and
NODESET
),andthemethodtakescareofreturninganobject
of the appropriate type.
XPathConstants
also declares a
NODE
constant, which
doesn'tmaptoaJavatype.Instead,it'susedtotell
evaluate()
thatyouonlywant
the resulting nodeset to contain a single node.
Aftercasting
Object
to
NodeList
,
main()
usesthisinterface's
getLength()
and
item()
methods to traverse the nodelist. For each item in this list,
getNodeValue()
iscalledtoreturnthenode'svalue,whichissubsequentlyoutput.
XPathDemo
generates the same output as
DOMDemo
.
Advanced XPath
TheXPathAPIprovidesthreeadvancedfeaturestoovercomelimitationswiththeXPath
1.0language.Thesefeaturesarenamespacecontexts,extensionfunctionsandfunction
resolvers, and variables and variable resolvers.
Namespace Contexts
When an XML document's elements belong to a namespace (including the default
namespace), XPath expressions that query the document must account for this
namespace. For nondefault namespaces, the expression doesn't need to use the same
namespaceprefix;itonlyneedstousethesameURI.However,whenadocumentspeci-
fiesthedefaultnamespace,theexpressionmustuseaprefixeventhoughthedocument
doesn't use a prefix.
<contacts xmlns="http://www.tutortutor.ca/">
tointroduceadefault
namespace. Furthermore, suppose that
Listing 10-22
included
dbf.setNamespaceAware(true);
after the line that instantiates
Docu-
mentBuilderFactory
. If you were to run the revised
XPathDemo
application
against the revised
contacts.xml
file, you would not see any output.
You can correct this problem by implementing
javax.xml.namespace.NamespaceContext
to map an arbitrary prefix to the
namespaceURI,andthenregisteringthisnamespacecontextwiththe
XPath
instance.