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

Local and global variables

Variables can be either local or global. Local variables are declared in a given template and they can be referenced only inside the template (in the part following the variable declaration).

Global variables are declared as children of the stylesheet element. They are visible in all templates.

In the example, xxx are local variables (They share the name but as they occur in different templates for the XSLT processor they have nothing in common. It would be an error to have local variables with the same name in the same template.)

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:variable  name="yyy">G</xsl:variable>

            <xsl:template  match="/aaa">
                  <xsl:apply-templates  select="*"/>
            </xsl:template>

            <xsl:template  match="bbb">
                  <xsl:variable  name="xxx">L-A</xsl:variable>
                  <bbb>
                        <local>
                              <xsl:value-of  select="$xxx"/>
                        </local>
                        <global>
                              <xsl:value-of  select="$yyy"/>
                        </global>
                  </bbb>
            </xsl:template>

            <xsl:template  match="ccc">
                  <xsl:variable  name="xxx">L-B</xsl:variable>
                  <ccc>
                        <local>
                              <xsl:value-of  select="$xxx"/>
                        </local>
                        <global>
                              <xsl:value-of  select="$yyy"/>
                        </global>
                  </ccc>
            </xsl:template>

      </xsl:stylesheet>
XML

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

      <bbb>
            <local>L-A</local>
            <global>G</global>
      </bbb>
      <ccc>
            <local>L-B</local>
            <global>G</global>
      </ccc>


Previous chapter: Named-Templates
Next chapter: Stylesheet Functions
Previous page: Variables
Next page: Setting variable value with select attribute