Navigating Along the preceding-sibling Axis

MSXML 5.0 SDK

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

Navigating Along the preceding-sibling Axis

Similar to the following-sibling:: axis, the preceding-sibling:: axis locates all nodes, elements, by default, which share the same parent node and which appear before the context node, in document order. Since the root node has no parent, it also has no preceding-siblings. If the context node is an attribute or namespace node, the preceding-sibling:: node locates an empty node-set.

You can override the default elements only selection of preceding-siblings by using the node() node test in the location step. For example, you can locate all of the root <chairman> element's preceding-sibling nodes of type element, node, or processing instruction (PI) using an XSLT template such as the one in the sample XSLT file.

The template rule in the sample XSLT file contains two references to the preceding-sibling:: axis. The first appears as the value of the <xsl:if> element's test attribute. It ensures that the template is instantiated in the result tree only if the context node has at least one node along the preceding-sibling:: axis.

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

XSLT File (orgchart-presibl.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="chairman">
    <xsl:if test="preceding-sibling::node()">
        <h2>preceding-siblings of '<xsl:value-of select="name"/>'</h2>
    <table border="1">
            <tr>
                <th>Node name</th>
                <th>Node value</th>
        </tr>
        <xsl:for-each select="preceding-sibling::node()">
            <tr>
               <td><xsl:value-of select="name()"/></td>
                <td><xsl:value-of select="."/></td>
            </tr>
        </xsl:for-each>
        </table>
   </xsl:if>
   <xsl:apply-templates/>
</xsl:template>

</xsl:stylesheet>

Formatted Output

Since the root element, by definition, has no siblings, the only node located along its preceding-sibling:: axis in this case is the <?xml-stylesheet?> processing instruction.

See Also

Navigating Along the following-sibling Axis