XPATH Briefly

XPath is a query language. It is used in various contexts in order to select particular nodes in an XML document. This is used in XSLT to invoke action on the selected XML. In XSLT the use is explified in three examples here:


<xsl:template match="/">
    <!-- some xslt action -->
</xsl:template>

<xsl:template match="title">
    <!-- some xslt action -->
</xsl:template>

<xsl:template match="memo/title">
    <!-- some xslt action -->
</xsl:template>

You may find examples similar to that in the assignments from the most recent chapter.

The XPath expressions are: /, title, and memo/title respectively. In addition to pointing to specific nodes in your document, it adds the tool to address particular occurences of elements by allowing you to specify predicates:


<xsl:template match="title[@priority='hot']">
    <!-- some xslt action -->
</xsl:template>

<xsl:template match="memo/para[first()]">
    <!-- some xslt action -->
</xsl:template>

<xsl:template match="memo[last()]/para[first()]">
    <!-- some xslt action -->
</xsl:template>

An XPath expression always evalutes to a path, a series of nodes in an XML document. Series are sorted and they contain no duplicates. The elements of a series always consist of:

axis::node[predicate]

A more concrete example could be:

child::memo/title[attribute::priority='hot']

Concretely this means the node memo/title with an attribute priority whose value is hot. The same thing would in a normal programming language be expressed with some if-statements. A predicate is an expression whose validation is subject to a concrete value of some variable. XPath supports twelve different axes. There are abbreviations, and wild cards available to create a more handy shorthand than the above concrete example. Any XPath expression is evaluated subject to a given context node. The possible axes are:

Example 41.1. Axes
child

Children of context node. Does not include attribute.

descendant

Children and childrens children etc. Also here: No attributes.

parent

Parent of context node. Empty if context node is root.

ancestor

All ancestors from parent through root.

following-sibling

Siblings to the right, hierarchically.

preceding-sibling

Siblings to the left, hierarchically.

following

Hierarchically later nodes excluding descendants.

preceding

Hierarchically earlier nodes excluding ancestors.

attribute

Attributes of the context node.

self

The context node if it needs referencing.

descendant-or-self

Concatenation of descendant and self.

ancestor-or-self

Concatenation of ancestor and self.