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

Navigating Along the preceding Axis

The preceding:: axis is the inverse of the following:: axis. It locates all nodes that come before the context node in document order. Ancestors, attribute nodes, and namespace nodes cannot be located along the context node's preceding:: axis.

In the sample organization chart document, if the context node is the <name> element containing "John Tippett," you can locate and display all preceding element nodes using the template rule shown below. This template rule creates a table in the result tree. Aside from the table headings, each row consists of the name of a preceding node, and that node's value. If the node name is "name", the row is colored yellow, otherwise white.

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

XSLT File (orgchart-prec.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[.='John Tippett']">
    <table border="1">
        <tr>
            <th>Node name</th>
            <th>Node value</th>
        </tr>
            <xsl:for-each select="preceding::*">
            <xsl:variable name="bgcolor">
                    <xsl:choose>
                        <xsl:when test="name()='name'">yellow</xsl:when>
                        <xsl:otherwise>white</xsl:otherwise>
                    </xsl:choose>
            </xsl:variable>
                <tr>
                    <xsl:attribute name="style">background-color: <xsl:value-of select="$bgcolor"/>
                    </xsl:attribute>
                    <td>
                        <xsl:value-of select="name()"/>
                    </td>
                    <td>
                        <xsl:value-of select="."/>
                    </td>
                </tr>
            </xsl:for-each>
        </table>
</xsl:template>

</xsl:stylesheet>

Formatted Output

See Also

Navigating Along the following Axis