How Do Global and Local Variables Differ in XSLT?

In XSLT, variables declared using the <xsl:variable> element act as immutable bindings whose accessibility and lifespan are determined entirely by where they are placed in the stylesheet. This article breaks down the fundamental differences between global and local XSLT variables, focusing on their declaration placement, scope and visibility, evaluation timing, and shadowing rules across templates.

Declaration and Placement

The primary syntactic difference between global and local variables lies in where the <xsl:variable> element is positioned relative to other elements in the stylesheet document:

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

    <!-- Global Variable -->
    <xsl:variable name="globalTaxRate" select="0.08" />

    <xsl:template match="order">
        <!-- Local Variable -->
        <xsl:variable name="itemTotal" select="price * quantity" />
        <total>
            <xsl:value-of select="$itemTotal + ($itemTotal * $globalTaxRate)" />
        </total>
    </xsl:template>

</xsl:stylesheet>

Scope and Visibility

Scope dictates which parts of the stylesheet can reference a variable using the $variableName syntax.

Feature Global Variables Local Variables
Visibility Visible throughout the entire stylesheet, across all templates and included/imported modules. Visible only to following sibling elements and their descendants within the enclosing container.
Order Dependency Can be referenced before or after their physical line of declaration in the stylesheet. Can only be referenced after their point of declaration; preceding elements cannot access them.
Parent Access Readily accessible from inside any child instruction block. Inaccessible outside the parent element in which they are defined.

In local scoping, placing an <xsl:variable> inside an <xsl:for-each> loop means the variable is re-bound for every iteration and cannot be read after the closing </xsl:for-each> tag.

Evaluation Timing and Context

While both global and local variables are strictly immutable once evaluated, their evaluation context differs:

Variable Shadowing Rules

XSLT defines strict rules regarding duplicate variable names: