XML technologies / XSLT / XSLT Cookbook / XPath / axes — effective use
(Excerpt from “XSLT Kochbuch” by Sal Mangano)
Problem
You need to select nodes in an XML tree while respecting the complex relationships in its hierarchy.
Solution
Each solution below is organised around related axes. Each group presents an example XML document with the context node highlighted. Path evaluation is explained, and nodes selected relative to the highlighted context are bold. Some examples use other context nodes to clarify subtleties of the path expression.
Child and descendant axes
The child axis is the default in XPath. You therefore need not write the axis specifier child::, although you may do so if you are feeling pedantic. The descendant:: and descendant-or-self:: axes go deeper into the XML tree. The first excludes the context node; the second includes it.
<Test id="descendants">
<parent>
<X id="1"/>
<X id="2"/>
<Y id="3">
<X id="3-1"/>
<Y id="3-2"/>
<X id="3-3"/>
</Y>
<X id="4"/>
<Y id="5"/>
<Z id="6"/>
<X id="7"/>
<X id="8"/>
<Y id="9"/>
</parent>
</Test>(: Auswählen aller Kindelemente namens X :)
X (: identisch mit child::X :)
Result: <X id="1"/> <X id="2"/> <X id="4"/> <X id="7"/> <X id="8"/>
(: Auswählen des ersten X-Kindelements :)
X[1]
Result: <X id="1"/>
(: Auswählen des letzten X-Kindelements :)
X[last( )]
Result: <X id="8"/>
(: Auswählen des ersten Elements, vorausgesetzt, es ist ein X. Ansonsten leer :)
*[1][self::X]
Result: <X id="1"/>
(: Auswählen des letzten Kindes, vorausgesetzt, es ist ein X. Ansonsten leer :)
*[last( )][self::X]
Result: ( )
(: Auswählen des letzten Kindes, vorausgesetzt, es ist ein Y. Ansonsten leer :)
*[last( )][self::Y]
Result:<Y id="9"/>
(: Auswählen aller Nachfahren namens X :)
descendant::X
Result: <X id="1"/> <X id="2"/> <X id="3-1"/> <X id="3-3"/> <X id="4"/> <X id="7"/> <X id="8"/>
(: Auswählen des Kontextknotens, falls dieser ein X ist, und aller Nachfahren namens X :)
descendant-or-self::X
Result: <X id="1"/> <X id="2"/> <X id="3-1"/> <X id="3-3"/> <X id="4"/> <X id="7"/> <X id="8"/>
(: Auswählen des Kontextknotens und aller Nachfahren :)
descendant-or-self::*
Result: <parent> <X id="1"/> <X id="2"/> <Y id="3"> <X id="3-1"/> <Y id="3-2"/> <X id="3-3"/> </Y> <X id="4"/> <Y id="5"/> <Z id="6"/> <X id="7"/> <X id="8"/> <Y id="9"/> </parent> <X id="1"/> <X id="2"/> <Y id="3"> <X id="3-1"/> <Y id="3-2"/> <X id="3-3"/> </Y> <X id="3-1"/> <Y id="3-2"/> <X id="3-3"/> <X id="4"/> <Y id="5"/> <Z id="6"/> <X id="7"/> <X id="8"/> <Y id="9"/>
Sibling axes
The sibling axes are preceding-sibling:: and following-sibling::. The preceding-sibling axis contains siblings before the context node; the following-sibling axis contains siblings (siblings) after it. Siblings are, of course, child nodes with the same parent. Most examples below use preceding-sibling::. You should have little trouble determining the results for following-sibling::.
Remember that a positional path expression of the form preceding-sibling::*[1] refers to the immediately preceding sibling of the context node, rather than the first sibling in document order. Confusion sometimes arises because the resulting sequence is in document order whether you use preceding-sibling:: or following-sibling::. Although not strictly an axis expression, ../X means “select preceding and following siblings named X, and the context node too if it is X”. More formally, it abbreviates parent::node( )/X. Note that (preceding-sibling::*)[1] and (following-sibling::*)[1] select the first preceding/following sibling in document order.
<!-- Beispieldokument mit hervorgehobenem Kontextknoten -->
<Test id="preceding-siblings">
<A id="1"/>
<A id="2"/>
<B id="3"/>
<A id="4"/>
<B id="5"/>
<C id="6"/>
<A id="7"/>
<A id="8"/>
<B id="9"/>
</Test>(: Auswählen aller A-Geschwisterknoten, die dem Kontextknoten vorangehen. :)
preceding-sibling::A
Result: <A id="1"/> <A id="2"/> <A id="4"/>
(: Auswählen aller A-Geschwisterknoten, die dem Kontextknoten folgen. :)
following-sibling::A
Result: <A id="8"/>
(: Auswählen aller Geschwisterelemente, die dem Kontextknoten vorangehen. :)
preceding-sibling::*
Result: <A id="1"/> <A id="2"/> <B id="3"/> <A id="4"/> <B id="5"/> <C id="6"/>
(: Auswählen des ersten vorhergehenden Geschwisterelements namens A in umgekehrter Dokumentenreihenfolge. :)
preceding-sibling::A[1]
Result: <A id="4"/>
(: Das erste vorhergehende Element in umgekehrter Dokumentenreihenfolge, vorausgesetzt, es ist ein A. :)
preceding-sibling::*[1][self::A]
Result:( )
(: Wenn der Kontext <A id="8"/> wäre, dann wäre das Ergebnis <A id="7"/> :)
(: Alle vorhergehenden Geschwisterelemente, die nicht A-Elemente sind: )
preceding-sibling::*[not(self::A)]
Result: <B id="3"/> <B id="5"/> <C id="6"/>
(: Benutzen Sie für die folgenden Rezepte dieses Dokument. :)
<Test id="preceding-siblings">
<A id="1">
<A/>
</A>
<A id="2"/>
<B id="3">
<A/>
</B>
<A id="4"/>
<B id="5"/>
<C id="6"/>
<A id="7"/>
<A id="8"/>
<B id="9"/>
</Test>
(: Das Element, das dem Kontext direkt vorausgeht, vorausgesetzt, es hat ein Kindelement A :)
preceding-sibling::*[1][A]
Result: ( )
(: Das erste Element, das dem Kontext vorausgeht, das ein Kind A hat :)
preceding-sibling::*[A][1]
Result: <B id="3"> ...
(: XPath 2.0 erlaubt eine größere Flexibilität bei der Auswahl von Elementen unter Beachtung von Namensräumen. Für diese Rezepte gilt das folgende XML-Dokument. :)
<Test xmlns:NS="http://www.ora.com/xstlcbk/1" xmlns:NS2="http://www.ora.com/xstlcbk/2">
<NS:A id="1"/>
<NS2:A id="2"/>
<NS:B id="3"/>
<NS2:B id="3"/>
</Test>(: Auswählen der vorhergehenden Geschwisterelemente des Kontexts, dessen Namensraum mit dem Präfix NS verknüpft ist :)
preceding-sibling::NS:*
Result: <NS:A id="1"/>
(: Auswählen der vorhergehenden Geschwisterelemente des Kontexts, dessen lokaler Name A ist :)
preceding-sibling::*:A
Result: <NS:A id="1"/>, <NS2:A id="2"/>
Parent and ancestor axes
The parent axis (parent::) refers to the parent of the context node. The expression parent::X must not be confused with ../X. The first yields a sequence of exactly one element if the context’s parent is X, or an empty sequence otherwise. The second abbreviates parent::node( )/X, selecting all siblings of the context node named X, including the context itself if it is X.
You can move to higher levels of the XML tree, such as parents, grandparents and great-grandparents, using either ancestor:: or ancestor-or-self::. The first excludes the context; the second includes it.
(: Auswählen des Elternknotens des Kontextknotens, vorausgesetzt, es ist ein X-Element. Ansonsten leer. :)
parent::X
(: Auswählen des Elternelements des Kontextknotens. Kann nur leer sein, wenn der Kontext das oberste Element ist. :)
parent::*
(: Auswählen des Elternknotens, wenn dieser in dem Namensraum liegt, der mit dem Präfix NS verknüpft ist. Das Präfix muss definiert sein, ansonsten tritt ein Fehler auf. :)
parent::NS:*
(: Auswählen des Elternknotens ungeachtet seines Namensraums, vorausgesetzt, der lokale Name ist X. :)
parent::*:X
(: Auswählen aller Vorfahrenelemente (einschließlich des Elternelements) namens X. :)
ancestor::X
(: Auswählen des Kontexts, vorausgesetzt, es ist ein X, und aller Vorfahrenelemente namens X. :)
ancestor-or-self::X
Preceding and following axes
The preceding and following axes can select many nodes because they cover nodes before or after the context in document order, excluding ancestors. The following axis excludes descendants, and the preceding axis excludes ancestors. Remember that both exclude namespace and attribute nodes.
(: Alle vorhergehenden Elementknoten namens X. :)
preceding::X
(: Der nächste vorhergehende Elementknoten namens X. :)
preceding::X[1]
(: Der am weitesten weg gelegene folgende Elementknoten namens X. :)
following::X[last( )]
Discussion
XPath uses axes to divide the document tree into subsets relative to a particular node, the context node. These subsets generally overlap, but ancestor, descendant, following, preceding and self partition the document, ignoring attribute and namespace nodes: they do not overlap and together contain every node. XPath establishes the context node. XSLT sets the context through:
a template selection (
<xsl:template match="x"> ... </xsl:template>)xsl:for-eachxsl:apply-templates
Effective use of the path expressions shown above is key to simple and complex transformations. Experience with traditional programming languages sometimes causes confusion and mistakes with XPath. For example, I have often caught myself writing: <xsl:if test="preceding-sibling::X[1]"> </xsl:if> when I meant <xsl:if test="preceding-sibling::*[1][self::X]"> </xsl:if>. Perhaps the second expression is the less intuitive way to say “test whether the immediately preceding sibling element is X”.
It is impossible to show every useful permutation of axis-based paths. Understanding these building blocks, however, puts you well on the way to decoding constructs such as preceding-sibling::X[1]/descendant::Z[A/B], or worse.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “XSLT Kochbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de