Previous | Next | Indexes
Zvon > Tutorials > XSLT 2.0 Tutorial > Variables and Parameters (6/14) >

Shadowing local variables

Value of a variable cannot be changed it can be only shadowed. The difference can be seen in the example. The second declaration of the variable "xxx" shadows the first one. The element ii is in scope of both the first and the second declaration and so the second one is used, the element yyy is only in scope of the second declaration.

This fact can cause problems for people used to other programming languages a rather surprising are demonstrated inside element zzz.

XSLT

      <xsl:stylesheet
                  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                  version="2.0">
            <xsl:output  method="xml"
                        indent="yes"
                        omit-xml-declaration="yes"/>

            <xsl:template  match="/aaa">
                  <xsl:variable  name="xxx">1</xsl:variable>
                  <xxx>
                        <i>
                              <xsl:value-of  select="$xxx"/>
                        </i>
                        <xsl:variable  name="xxx"
                                    select="$xxx + 5"/>
                        <ii>
                              <xsl:value-of  select="$xxx"/>
                        </ii>
                  </xxx>
                  <yyy>
                        <xsl:value-of  select="$xxx"/>
                  </yyy>
                  <zzz>
                        <xsl:variable  name="i"
                                    select="1"/>
                        <xsl:for-each  select="1 to 5">
                              <xsl:variable  name="i"
                                          select="$i+1"/>
                              <j>
                                    <xsl:value-of  select="$i"/>
                              </j>
                        </xsl:for-each>
                        <jjj>
                              <xsl:value-of  select="$i"/>
                        </jjj>
                  </zzz>
            </xsl:template>

      </xsl:stylesheet>
XML

      <aaa>
            <bbb/>
            <bbb/>
            <bbb/>
      </aaa>
Output

      <xxx>
            <i>1</i>
            <ii>6</ii>
      </xxx>
      <yyy>1</yyy>
      <zzz>
            <j>2</j>
            <j>2</j>
            <j>2</j>
            <j>2</j>
            <j>2</j>
            <jjj>1</jjj>
      </zzz>


Previous chapter: Named-Templates
Next chapter: Stylesheet Functions
Previous page: Variable shadowing
Next page: Nodes as variable values