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

Determining the Context Node

The context node of an XML Path Language (XPath) location path is the node relative to the expression being evaluated.

In lengthy XPath expressions, the context node implicitly changes as the processor hits various steps in moving along the expression from left to right. For example, consider the expression:

attribute::scale/ancestor::weather/forecast[position()=2]/attribute::day

For XSLT, understanding the context node, and knowing what it is at any given point, is critical to successful use of the standard.

Example

In the following XSLT file, the XPath expressions appear as bold text.

XSLT File (weathersimple.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="temperature">
    Today<xsl:choose>
        <xsl:when test="name(..)='today'">'s </xsl:when>
        <xsl:otherwise ><xsl:value-of select="../@day" />'s </xsl:otherwise>
    </xsl:choose>
temperature: <xsl:value-of select="." /><br />
</xsl:template>

</xsl:stylesheet>

What is displayed in the result tree by this template rule depends entirely on the context node. The template rule matches a single element type in the source tree, <temperature>, and the corresponding match pattern (match="temperature") is what establishes the context node within the body of the template rule. However, the <temperature> element type can be a child of either the <today> element or a <forecast> element, and the <xsl:choose> element operates accordingly:

If the context node did not change each time this template rule fired, it would not be possible to produce different output for each occurrence of the <temperature> element.

XML File (weather.xml)

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

Formatted Output

Today's temperature: 76
Today+1's temperature: 81
Today+2's temperature: 72

Processor Output

<?xml version="1.0" encoding="UTF-16"?>
    Today's 
temperature: 76<br />
    Today+1's 
temperature: 81<br />
    Today+2's 
temperature: 72<br />