Java Reference
In-Depth Information
Selecting XML Document Nodes with XPath
XPath
isanonXMLdeclarativequerylanguage(definedbytheW3C)forselectingan
XMLdocument'sinfosetitemsasoneormorenodes.Forexample,youcanuseXPath
XPath is often used to simplify access to a DOM tree's nodes, and is also used in
thecontextofXSLT(discussedinthenextsection),typicallytoselectthoseinputdoc-
ument elements (via XPath expressions) that are to be copied to an output document.
Java 7 supports XPath 1.0 via JAXP's XPath API, which is assigned package
javax.xml.xpath
.
This section first acquaints you with the XPath 1.0 language. It then demonstrates
howXPathsimplifiestheselectionofaDOMtree'snodes.Lastly,thesectionintroduces
you to three advanced XPath topics.
XPath Language Primer
XPath views an XML document as a tree ofnodes that starts from a root node. XPath
recognizessevenkindsofnodes:element,attribute,text,namespace,processinginstruc-
tion,comment,anddocument.XPathdoesnotrecognizeCDATAsections,entityrefer-
ences, or document type declarations.
Note
A tree's root node (a DOM
Document
instance) is not the same as a doc-
ument's root element. The root node contains the entire document, including the root
element,anycommentsorprocessinginstructionsthatappearbeforetherootelement's
start tag, and any comments or processing instructions that appear after the root ele-
ment's end tag.
XPathprovideslocationpathexpressionsforselectingnodes.A
location path expres-
sion
locatesnodesviaasequenceof
steps
startingfromthe
context node
(therootnode
orsomeotherdocumentnodethatisthecurrentnode).Thereturnedsetofnodesmight
be empty, or it might contain one or more nodes.
Thesimplestlocationpathexpressionselectsthedocument'srootnodeandconsists
of a single forward slash character (
/
). The next simplest location path expression is
thenameofanelement,whichselectsallchildelementsofthecontextnodethathave
that name. For example,
ingredient
refers to all
ingredient
child elements of
thecontextnodein
Listing10-1
'sXMLdocument.ThisXPathexpressionreturnsaset
of three
ingredient
nodes when
ingredients
is the context node. However, if
recipe
or
instructions
happenedtobethecontext node,
ingredient
would
notreturnanynodes(
ingredient
isachildof
ingredients
only).Whenanex-