↑
Main Page
Introduction to XPath
Introduction to XPath
Every XPath expression has two parts: a context node and a node pattern. The context node provides the
context from which the node pattern should begin. The node pattern is a string made up of one or more
node selectors.
For instance, consider the following XML document:
<?xml version=”1.0”?>
<employees>
<employee title=”Software Engineer”>
<name>Nicholas C. Zakas</name>
</employee>
<employee title=”Salesperson”>
<name>Jim Smith</name>
</employee>
</employees>
And consider this XPath expression:
employee/name
If the context node is
<employees/>
, then the previous XPath expression matches both
<name>Nicholas
C. Zakas</name>
and
<name>Jim Smith</name>
. In the expression, both
employee
and
name
refer to
tag names of XML elements in the order in which they appear from the context node; the slash indicates a
parent-to-child relationship. In essence, the XPath expression says, “Starting from
<employees/>
, match
any
<name/>
elements located under any
<employee/>
element that is a child of the reference node.”
To select only the first
<employee/>
element’s
<name/>
element, the XPath expression is the following:
employee[position() = 1]/name
In XPath, the square brackets notation is used to provide more specific information about an element.
This example uses the XPath
position()
function, which returns the element’s position under its
parent element. The first child node is in position
1
, so comparing
position()
to
1
matches only the
first
<employee/>
element. Then, the slash and
name
match the
<name/>
element under that first
<employee/>
element.
You can use a variety of ways to match elements in addition to their names and positions. Suppose you
want to select all
<employee/>
elements with the
title
attribute equal to
“Salesperson”
, the XPath
expression would be the following:
employee[@title = “Salesperson”]
In this expression, the
@
symbol is short for
attribute
.
XPath is a very powerful expression that can make finding specific nodes within a DOM Document
much easier. Because of this, both IE and Mozilla made sure to include XPath support in their DOM
implementations.
If you’d like to learn more about XPath, consider picking up XPath 2.0: Programmer’s Reference (Wiley
Publishing, Inc., ISBN 0-7645-6910-4).
466
Chapter 15
18_579088 ch15.qxd 3/28/05 11:42 AM Page 466
Free JavaScript Editor
Ajax Editor
©
→