xsltxsl-variable

xsl:variable assignment clarification


My understanding is that <xsl:variable> is immutable and cannot be reassigned.

I am new to XSL and came across a situation like what is in the example below.

<xsl:stylesheet>

  <xsl:variable name="temp" select="true()"/>

  <xsl:template name="example">
     <xsl:variable name="temp" select="false()"/>
     <p><xsl:value-of select="$temp"/></p>
  </xsl:template>

</styleheet>

I have not found anything definitive as to why this occurs. The only way I can reason that I'm not getting an error and why temp will output false is that there is a global temp variable AND an a local temp variable (and somehow are not colliding).

Why am I able to "reassign" temp?


Solution

  • You are able to "reassign" (more precisely, to shadow) the variable, because the first binding is at the top-level of the stylesheet, while the second one is in a template.

    From XSLT 1.0 specification:

    A binding shadows another binding if the binding occurs at a point where the other binding is visible, and the bindings have the same name. It is an error if a binding established by an xsl:variable or xsl:param element within a template shadows another binding established by an xsl:variable or xsl:param element also within the template. It is not an error if a binding established by an xsl:variable or xsl:param element in a template shadows another binding established by an xsl:variable or xsl:param top-level element.