Using Variables as Convenience Constants

MSXML 5.0 SDK

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

Using Variables as Convenience Constants

Suppose we want to replace the generic location names in the XSLT style sheet in Initial XSLT Example Using Variables (weatherlogv1.xsl) with more descriptive names, so that "location1", "location2", and "location3" are mapped to "Midtown", "Northest", and "Airport", respectively, for the place attribute of the locale elements. We can do this with the help of an XSLT variable, placename. The changes affect the template rule for the weather element. The revised template rule is shown below. Changes are in bold.

<xsl:template match="weather">
   <H1>Weather Readings</H1>
   <xsl:for-each select="day">
      <H2>As of <xsl:value-of select="@date"/></H2>
      <xsl:for-each select="locale">
         <xsl:variable name="placename">
             <xsl:choose>
                 <xsl:when test="@place='location1'">Midtown</xsl:when>
                 <xsl:when test="@place='location2'">Northeast</xsl:when>
                 <xsl:when test="@place='location3'">Airport</xsl:when>
                 <xsl:otherwise>[Unknown Locale]</xsl:otherwise>
             </xsl:choose>
         </xsl:variable>
         <H3><xsl:value-of select="$placename"/></H3>
      </xsl:for-each>
   </xsl:for-each>
</xsl:template>

For each <locale> element, we have declared a placename variable, and assigned it a value based on the value of its place attribute. This variable value ($placename) is then used as the output of the new location name.

Formatted Output

With the revised the XSLT style sheet, the result is as follows:

The variable declaration above can be converted to a named template, and placed outside the template rule. This makes its value accessible anywhere in the style sheet. For more information, see Using Parameters to Store Values that Change.

See Also

Initial XSLT Example Using Variables | Finished XSLT Example Using Variables