2007-03-20
Tyng-Ruey Chuang,
<trc@iis.sinica.edu.tw>
Institute of Information Science
Academia Sinica, Taipei, Taiwan
XPath models an XML document as a tree. The tree contains 7 types of node:
the root node
element nodes
text nodes
attribute nodes
namespace nodes
processing instruction nodes
comment nodes
The root node and element nodes have an order list of child nodes. Note that XPath operates on an XML document after CDATA sections, entity references, and document type declarations have been merged into the document.
An XPATH location path identifies a set of nodes in a document. A location path is built out of successive location steps. Each step is evaluated relative to a particular node in the document called the context node.
The root location path: /
Child element location steps. Examples:
/people/person
/people/person/name
Attribute location steps. Examples:
/people/person/@born
/people/person/@id
The comment()
, text()
, and
processing-instruction()
location steps. Example:
/people/person/profession/text()
Wildcards: *
, node()
, @*
. Examples:
/people/person/*
/people/person/@*
Multiple matches with |
. Example:
//first_name | //last_name
Try them on! Use this example document on this XPath evaluator!
XPATH expressions can be formed just like Unix path expressions using /, .., ., and //. The last one, for all descendants of the context node, is new! Examples:
//name//*
//name/../profession/.
Each step in a location path may (but does not have to) have a predicate that selects from the node-set current at that step in the expression. Examples:
//person[@id = "p4567"]
//person[@born<=1920 and @born >= 1915]
/people/person[position()=1]/profession[position()=3]
The following abbreviated XPath expression
//person[@born<1950]/name
is the same as the following unabbreviated XPath expression
/descendant::person[attribute::born < 1950]/child::name
There are 13 axes:
ancestor
ancestor-or-self
attribute
child
descendant
descendant-or-self
following
following-sibling
namespace
parent
preceding
preceding-sibling
self