Navigating Along the ancestor-or-self Axis

MSXML 5.0 SDK

Microsoft XML Core Services (MSXML) 5.0 for Microsoft Office - XPath Developer's Guide

Navigating Along the ancestor-or-self Axis

The ancestor-or-self:: axis, like the ancestor:: axis, locates all nodes in the document hierarchy above the context node. It locates the parent of the context node, the parent's parent, and so on up to the root node. Unlike ancestor::, however, ancestor-or-self:: also selects the context node itself.

Attribute and namespace nodes cannot be located along the ancestor-or-self:: axis, unless the context node is itself an attribute or namespace node. In the latter case, the context node is located because of the or-self component of this axis.

Again referring to our sample XML document, who is in the "chain of command" responsible for setting Josh Barnhill's goals and objectives? You can answer this question with a template rule such as the XSLT file shown below.

The position() and last() functions are used to calculate the number of steps above "Josh Barnhill". For more information, see Using Functions in XPath Expressions.

Example

XML File (orgchart.xml)

Use orgchart.xml (in Sample XML File for Navigating XPath Axes) and edit its href attribute to refer to orgchart-ancself.xsl.

XSLT File (orgchart-ancself.xsl)

<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!-- suppress text nodes not covered in subsequent template rule -->
<xsl:template match="text()"/>

<xsl:template match="name[.='Josh Barnhill']">
    <h2>Josh Barnhill's reporting structure:</h2>
    <table border="1">
        <tr>
            <th>Generation</th>
            <th>Name</th>
            <th>Emp ID</th>
            <th>Empl Date</th>
        </tr>
        <xsl:for-each select="ancestor-or-self::*[name()!='name']">
            <tr>
                <td align="center">
                    <xsl:value-of select="position()-last()"/>
                </td>
                <td><xsl:value-of select="name"/></td>
                <td><xsl:value-of select="@empID"/></td>
                <td><xsl:value-of select="@empdate"/></td>
            </tr>
        </xsl:for-each>
    </table>
</xsl:template>

</xsl:stylesheet>

Formatted Output

See Also

Navigating Along the ancestor Axis