XML technologies / XSLT / Reference: XSLT 1.0 and 2.0 elements / variable

(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 6.)

A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z

 

Instruction xsl:variable defines a named variable whose value cannot change during its lifetime. It may be global or local to a template rule.

Classification

Declaration/instruction

Function group

Variable definition

Introduced in

XSLT 1.0

Stylesheet position and permitted contents:

xsl:variable occurs as a top-level element or instruction. As a child of xsl:stylesheet or xsl:transform, it creates a global variable. Inside template rule xsl:template it creates a local variable valid for that rule.

The element must be empty with attribute select. Without attribute select, it must contain a sequence-constructor body mixing XSLT instructions, text and literal result elements. This builds a temporary tree accessible through the variable.

Attributes:

For xsl:variable, standard attributes apply, plus mandatory attribute name and optional attribute select. XSLT 2.0 adds attribute as specifying the required datatype.

as

Value

sequence-type

Usage

optional

Introduced in

XSLT 2.0

Attribute as specifies the variable datatype as an XPath 2.0 sequence type. The value must match it when as is present.

Otherwise no conversion is attempted. A failed conversion is a type error (ERR XTTE0590). Without attribute as, the value is taken unchanged from the evaluated select expression or constructor.

Note: The attribute does not exist in XSLT 1.0.

name

Value

qname

Usage

mandatory

Introduced in

XSLT 1.0

Mandatory attribute name gives the reference name, a QName. Same-named variables at equal import precedence or scope (scope) are forbidden: no duplicate globals or locals in one template. Violations are static errors (ERR XTSE0580).

Duplicate names are allowed in these cases:
Same-named globals must have different import precedences. Imported duplicates use the highest-precedence value, normally the principal module’s. Lower values are inaccessible.

A local variable may share a global name, shadowing it (shadows) within its template. The global value is inaccessible there.

Locals in different template rules may share names because scopes do not overlap. Each exists only during its own rule’s execution.

select

Value

xpath-expression

Usage

optional

Introduced in

XSLT 1.0

Attribute select creates the value instead of a constructor inside xsl:variable. It contains an XPath expression evaluating to that value. With attribute select, the element must be empty, though the specification provides no explicit error message.

Evaluation yields a sequence. Numbers can be literals; string literals need quotes in addition to attribute delimiters:

<xsl:variable name=stringvariable select="'mein stringwert'"/>

Purpose:

A variable is named value storage. XSLT differs because assignment occurs once, at declaration, and the value cannot later change.

Values therefore cannot be reassigned or accumulated. (Note: Processor extensions, for example in Saxon, allow runtime reassignment using saxon:assign for variables marked by saxon:assig-nable="yes". Standard XSLT has no plans for this because it violates freedom from side effects.) Even a simple i++ counter requires indirect recursive template calls.

XSLT variables thus resemble constants, marked in C++ with const and in Java with final.

Naming and referencing:
A variable is named with attribute name. Its QName may include a prefix bound to a namespace. Reference its name preceded by $ in any XPath expression or AVT:

<xsl:variable name="beispielvariable" select="der_wert"/>
<!-- Referenzierung -->
<xsl:value-of select="$beispielvariable"/>

Warning – References do not distinguish xsl:param:
References do not distinguish variables from parameters. A reference to $x does not reveal whether declared by <xsl:variable name="x"> or <xsl:param name="x">. Therefore same-named variables and parameters also collide or shadow each other.

Variable scope:
Variables have strictly regulated scope (scope): readable inside, invisible or nonexistent outside.

Stylesheets and rules execute sequentially. The processor neither looks ahead for declarations nor goes back to insert a reference before a declaration.

Rule of thumb for scope:
Scope begins at the declaration and includes following siblings (following siblings) and their descendants (descendants).

A common mistake is trying two conditional declarations to give a variable alternative values. This does not work:

...
<xsl:choose>
  <xsl:when test="bedingung1">
    <xsl:variable name="so_nicht" select="wert1"/>
  </xsl:when>
  <xsl:when test="bedingung2">
    <xsl:variable name="so_nicht" select="wert2"/>
  </xsl:when>
</xsl:choose>
...
<!-- die Referenzierung von $so_nicht schlägt fehl: -->
<xsl:value-of select="$so_nicht"/>

Different declarations within instructions xsl:when are legal but fail here: when referenced, variable $so_nicht is already out of scope. By the rule following-sibling, it could be referenced only inside the respective xsl:when containers.

Note: Example 1 gives a working alternative-value assignment.

Declaration location determines whether a variable is global or local.

Global variables

To be readable everywhere, xsl:variable must be top-level. Put it near the beginning so it applies to following elements and children. Since all elements xsl:template are following siblings of the declaration, the variable applies in all following templates:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:variable name="var_global" select="'der_wert'"/>
  <!-- Referenzierung überall im Stylesheet mit $var_global -->
</xsl:stylesheet>

Global references are unavailable in rules declaring a same-named local variable or same-named local parameter, which shadows the global. Its value cannot be accessed there.

Local variables

A variable declared inside template rule xsl:template is local to it while active, limited to following siblings within its block. Declare it near the start, after local parameters.

Their order affects neither value passing nor referencing.

<xsl:template match="beispiel">
  <!-- hier evtl. lokale Parameter -->
  <xsl:variable name="var1" select="'wert_1'"/>
  <xsl:variable name="varm2" select="'wert_2'"/>
  ...
  <!-- Referenzierung mit $var1 und $var2 -->
</xsl:template>

Each call initializes locals anew. Values remain unchanged during execution. Before and after instantiation, locals do not exist and are inaccessible outside the rule.

Other rules may safely use identical local names because scopes do not overlap. Within its rule, a local overrides a same-named global variable or parameter.

Referencing in another variable declaration:
One variable can help compute another. For globals, respect order: if variable $a supplies its value to declaration $b, it must already be declared to be referenced:

<xsl:variable name="b" select="$a * 2"/>

Circular definitions are forbidden. A variable cannot reference itself within its declaration or value-generating body because it is not in scope there.

Examples:

Example 1 – Assigning alternative values:

<!-- Lösung mit XSLT 1.0 -->
<xsl:variable name="maximum">
  <xsl:choose>
    <xsl:when test="$wert1 &gt; $wert2">
      <xsl:value-of select="$wert1"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$wert2"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:variable>

This XSLT 1.0 method assigns variable $maximum either value $wert1 or $wert2. It works in XSLT 2.0 too but is verbose.

The xsl:choose selection block must be inside the variable instruction. Alternative declarations inside instructions xsl:when cannot be used to choose between them.

XSLT 2.0 has a simpler solution replacing xsl:choose with an XPath expression:

<!-- Lösung mit XPath 2.0 -->
<xsl:variable name="maximum" select="if($wert1 &gt; $wert2) then $wert1 else $wert2"/>

This is not backward-compatible. Function fn:max() simplifies it further:

<!-- Lösung mit XPath 2.0 -->
<xsl:variable name="maximum" select="fn:max(($wert1, $wert2))"/>

and can return the maximum of a sequence $eingabesequenz of any size rather than just two values:

<!-- allgemeine Lösung mit XPath 2.0 -->
<xsl:variable name="maximum" select="fn:max($eingabesequenz)"/>
  

Example 2 – A global variable:

<xsl:variable name="ausrichtung">center</xsl:variable>
<!-- eine von vielen Template-Regeln -->
<xsl:template match="abschnitt">
  <p align="{$ausrichtung}"><xsl:apply-templates/></p>
</xsl:template>

Global variable $ausrichtung is referenced in a literal element’s AVT in one template, but is available to every rule.

To change alignment of all elements <p>, change only the variable’s stylesheet value. For external configuration at invocation, use a global parameter instead.

Example 3 – Shadowing between global and local variables:

<!-- globale Variable -->
<xsl:variable name="die_variable" select="globaler_wert"/>
<xsl:template name="template_a">
  <xsl:variable name="die_variable" select="lokaler_wert"/>
  ...
  <!-- Referenz bezieht sich auf lokale Variable: -->
  Lokal: <xsl:value-of select="$die_variable"/>
</xsl:template>
<xsl:template name="template_b">
  <!-- Referenz bezieht sich auf globale Variable: -->
  Global: <xsl:value-of select="$die_variable"/>
</xsl:template>

Variable $die_variable is both global and local in one rule. Only the local value is available there (shadowing); the global value cannot be accessed.

Example 4 – Storing intermediate values:

<xsl:template name="listenausgabe">
  <xsl:param name="liste"/>
  <xsl:variable name="token" select="fn:substring-before($liste, ' ')"/>
  <xsl:variable name="rest" select="fn:substring-after($liste, ' ')"/>
  <!-- der erste Teil der Liste wird ausgegeben: -->
  <xsl:value-of select="$token"/>
  <!-- prüfen, ob Rest geblieben ist ... -->
  <xsl:if test="$rest">
    <!-- Break ausgeben: -->
    <br/>
    <!-- ... und Template wieder aufrufen: --> 
    <xsl:call-template name="listenausgabe">
      <!-- Rest der Liste als neuen Anfangswert übergeben: -->
      <xsl:with-param name="liste" select="$rest"/>
    </xsl:call-template>
  </xsl:if>
<xsl:template>

Two string-operation results are stored in locals and reused in one rule. Without them the same expressions would need repeated evaluation.

This excerpt recursively processes a string. The full example is example 2 under function fn:substring-after().

Example 5 – Simulating a counter:

<xsl:template name="zaehler">
  <!-- beim Start ist der Zähler 0: -->
  <xsl:param name="der_zaehler" select="0"/>
  <!-- neue Variable – hier wird gezählt: -->
  <xsl:variable name="neuer_zaehler" select="$der_zaehler + 1"/>
  <!-- Abbruchbedingung prüfen: -->
  <xsl:if test="$neuer_zaehler &lt; 10">
    <ausgabe>Der Zählerstand ist <xsl:value-of select="$neuer_zaehler"/></ausgabe>
    <!-- Template wieder aufrufen -->
    <xsl:call-template name="zaehler">
      <!-- den Zählerstand übergeben: -->
      <xsl:with-param name="der_zaehler" select="$neuer_zaehler"/>
    </xsl:call-template>
  </xsl:if>
</xsl:template>

A named template can simulate a counter by calling itself with its last count as an input parameter.

The ending condition xsl:if or a similar construct is essential to stop endless recursive calls. Formulate a termination condition, just as for loops of type while or do ... while in any language.

Example 6 – Storing a document reference:

<xsl:variable name="das_dokument" select="docu¬ment('extern.xml')"/>
<xsl:template name="externes_dokument">
  <!-- Zugriff auf das Dokument -->
  <xsl:apply-templates select="$das_dokument"/>
</xsl:template>

The document in variable $das_dokument is accessed like one directly referenced by document('extern.xml'). Keeping a frequently used document in a variable, perhaps global, is convenient.

Element definition:

XSLT 1.0:

<!-- Category: top-level-element/instruction -->
<xsl:variable 
     name = qname 
     select = expression>

     <!-- Content: template -->
</xsl:variable>

XSLT 2.0:

<!-- Category: declaration/instruction -->
<xsl:variable
     name = qname
     select? = expression
     as? = sequence-type>

    <!-- Content: sequence-constructor -->
</xsl:variable>

   

  

back to top