node Selects all child elements with a given node name
* Selects all child elements
@attr Selects an attribute
@* Selects all attributes
ns:* Selects elements in a given namespace
node() Matches an element node
text() Matches a text node
comment() Matches a comment node
processing-instruction() Matches a processing instruction node
. (dot) Selects the current node
.. (double dots) Selects the parent of the current node
/ (slash) Selects the document node
// (double slash) Selects descendants and self-which is equivalent to descendant-or-self
Note that because the default axis is child, when an axis is omitted, the child axis is used. The XML document fragment mentioned in the previous section is used to demonstrate how to use these basic patterns. The following table lists a set of example XPath patterns and the element nodes selected based on these shortcuts.
Example XPath Patterns
/ is equal to /child and selects all the children of the root (the date element and the two customer elements in our sample document). /customer selects all the customer elements that are children of the root-in this case, there are two customer elements.
Selects all the order elements that are descendants of the root (document) node-in this case, there are two order elements.
/.//order is equivalent to /self::node()/descendant- or-self/child/order. /self::node() is the root node, /self:: node()/descendant-or-self selects all of the descendant elements of the root and the root itself, and /self::node()/descendant-or-self/child/order selects the order elements that are descendants of the root.
|/.//order[@orderID =o100]../customer||/.//order selects the two order elements. [@orderID=o100] selects the order element with an attribute named orderID that has a value equal to o100 (the first order element in the document). .. selects the parent element, /.//order[@orderID =o100]../customer selects the customer element containing the order element with an orderID attribute equal to o100.|
Selects all the elements that are descendants of the root element and that have a customerID attribute (the two customer elements).
Selects all the children of the root element (the twocustomer elements and the date element).
Selects all the order elements that are grandchildren of the root element (in this case, the two order elements).
//order/ selects the second order element, //order/@orderID retrieves the value of the orderID attribute for the second order element.
XPath also contains functions. These functions will be discussed when we discuss XSL in Chapter 12.