Navigating Along the ancestor Axis

MSXML 5.0 SDK

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

Navigating Along the ancestor Axis

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. The root node is an ancestor of all other nodes in the document, and itself has no ancestors.

Because ancestor:: extends the parent:: axis all the way back through the document tree, all limitations and effects of the parent:: axis apply to the ancestor:: axis as well.

If you wanted to show the names of all employees along the ancestor axis of the employee whose name is Peter Porzuczek—that is, all of Peter Porzuczek's supervisors—you could use the sample XSLT template rule below.

The ancestors are retrieved in reverse document order. That is, the ancestor closest to context node is displayed first, followed by that ancestor's parent, followed by its parent's parent.

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-ancestor.xsl.

XSLT File (orgchart-ancestor.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='Peter Porzuczek']">
    <h2>Peter Porzuczek's superiors:</h2>
        <xsl:for-each select="ancestor::*">
            <h4><xsl:value-of select="name"/></h4>
        </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Formatted Output

See Also

Navigating Along the parent Axis