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

Determining the Context Position

Similar to context size, context position, where you are in the node-set, is as important in determining what a style sheet needs at any one time. A typical example can be performing an action for every Nth node.

You can use the Sample XML Data File for XPath Context and Navigation, to display information for each day on a separate line, coloring the odd lines white and the even lines yellow. This provides easy legibility when there are a large amount of data to be displayed. Use the following XSLT template rule to display just the temperature values:

The following template rule display just the temperature values:

Note   The use of the position() function in the <xsl:variable> code.

For more information about position(), see Processing Node-Sets by Using Node-Set Functions.

Example

XML File (weather.xml)

Change the href attribute in weather.xml (shown in Sample XML Data File for XPath Context and Navigation) to reference weathercontextposn.xsl.

XSLT File (weathercontextposn.xsl)

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="weather/*">
    <xsl:variable name="odd_or_even">
        <xsl:choose>
            <xsl:when test="position() mod 2 = 0">even</xsl:when>
            <xsl:otherwise>odd</xsl:otherwise>
        </xsl:choose>
    </xsl:variable>
    <xsl:choose>
        <xsl:when test="$odd_or_even = 'even'">
            <p style="background-color: yellow">even row: 
                <xsl:value-of select="./temperature" />
            </p>
        </xsl:when>
        <xsl:otherwise>
            <p style="background-color: white">odd row: 
                <xsl:value-of select="./temperature" />
            </p>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>

Formatted Output

Processor Output

<?xml version="1.0" encoding="UTF-16"?><p style="background-color: white">odd row: 
                76</p><p style="background-color: yellow">even row: 
                81</p><p style="background-color: white">odd row: 
                72</p>