The child axis is the default axis in XPath. This means one does not need to use the child:: axis specification. One can reach deeper into the XML tree using the descendant:: and the descendant-or-self:: axes.

Input

<Records>
    <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"/>
</Records>

 

Examples

/Records is the context node, thus selections are performed relative to this element.

We have written example statements according to this assumption. Nonetheless, we will include it in XPath expressions to represent the full location.

 

> Select all child elements named X

/Records/X

Result:

<X id="1"/>
<X id="2"/>
<X id="4"/>
<X id="7"/>
<X id="8"/>

 

> Select the first X child element

/Records/X[1]

Result:

<X id="1"/>

 

> Select the last X child element

/Records/X[last()]

Result:

<X id="8"/>

 

> Select the first element, provided it is an X. Otherwise empty

/Records/*[1][self::X]

Result:

<X id="1"/>

 

> Select the last child, provided it is an X. Otherwise empty

/Records/*[last()][self::X]

Result:

 

> Select the last child, provided it is an Y. Otherwise empty

/Records/*[last()][self::Y]

Result:

<Y id="9"/>

 

> Select all descendants named X

/Records/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"/>

 

> Select the context node, if it is an X, and all descendants named X

/Records/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"/>

 

> Select the context node and all descendant elements

/Records/descendant-or-self::*

Result:

<Records>
    <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"/>
</Records>
<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"/>