The parent axis (parent::) refers to the parent of the context node. The expression parent::X should not be confused with ../X. The former will produce a sequence of exactly one element provided the parent of the context is X or empty otherwise. The latter is a shorthand for parent::node( )/X, which will select all siblings of the context node named X, including the context itself, should it be an X.

One can navigate to higher levels of the XML tree (parents, grandparents, great-grandparents, and so on) using either ancestor:: or ancestor-or-self::. The former excludes the context and the latter includes it.

Input

<Records>
    <A id="1"/>
    <A id="2">
        <A id="2.1"/>
        <A id="2.2"/>
        <B id="2.3"/>
    </A>
    <B id="3"/>
</Records>

 

Examples

/Records/A[2]/A[2] 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 the parent of the context node, provided it is an A element. Empty otherwise.

/Records/A[2]/A[2]/parent::A

Result:

<A id="2">
        <A id="2.1"/>
        <A id="2.2"/>
        <B id="2.3"/>
    </A>

 

> Select the parent element of the context node. Can only be empty if the context is the top-level element.

/Records/A[2]/A[2]/parent::*

Result:

<A id="2">
        <A id="2.1"/>
        <A id="2.2"/>
        <B id="2.3"/>
    </A>

 

> Select all ancestor elements (including the parent) named A.

/Records/A[2]/A[2]/ancestor::A

Result:

<A id="2">
        <A id="2.1"/>
        <A id="2.2"/>
        <B id="2.3"/>
    </A>

 

> Select the context, provided it is an A, and all ancestor elements named A.

/Records/A[2]/A[2]/ancestor-or-self::A

Result:

<A id="2">
        <A id="2.1"/>
        <A id="2.2"/>
        <B id="2.3"/>
    </A>
<A id="2.2"/>

 

Leave a Reply

Close Menu