XSLT Variables Overview
In XSLT scripts, you declare variables using the <xsl:variable>
element. The name
attribute specifies the name of the variable, which is case-sensitive.
Once you declare a variable, you can reference it within an XPath expression using the variable name prefixed
with a dollar sign ($).
Variables are immutable; you can set the value of a variable
only when you declare the variable, after which point, the value is
fixed. You initialize a variable by including the select
attribute and an expression in the <xsl:variable>
tag. The following example declares and initializes the variable location
. The location
variable
is then used to initialize the message
variable.
<xsl:variable name="location" select="$dot/@location"/> <xsl:variable name="message" select="concat('We are in ', $location, ' now.')"/>
You can define both local and global variables. Variables are
global if they are children of the <xsl:stylesheet>
element. Otherwise, they are local. The value of a global variable
is accessible anywhere in the style sheet. The scope of a local variable
is limited to the template or code block in which it is defined.
XSLT variables can store any values that you can calculate or statically define. This includes data structures, XML hierarchies, and combinations of text and parameters. For example, you could assign the XML output of an operational mode command to a variable and then access the hierarchy within the variable.
The following template declares the message
variable. The message
variable includes
both text and parameter values. The template generates a system log
message by referring to the value of the message variable.
<xsl:template name="emit-syslog"> <xsl:param name="user"/> <xsl:param name="date"/> <xsl:param name="device"/> <xsl:variable name="message"> <xsl:text>Device </xsl:text> <xsl:value-of select="$device"/> <xsl:text> was changed on </xsl:text> <xsl:value-of select="$date"/> <xsl:text> by user '</xsl:text> <xsl:value-of select="$user"/> <xsl:text>.'</xsl:text> </xsl:variable> <syslog> <message> <xsl:value-of select="$message"/> </message> </syslog> </xsl:template>
The resulting system log message is as follows:
Device device-name was changed on date by user 'user.'
Table 1 provides examples of XSLT variable declarations along with pseudocode explanations.
Variable Declaration |
Pseudocode Explanation |
---|---|
|
Assigns the |
|
Assigns the value of the |