Help us improve your experience.

Let us know what you think.

Do you have time for a two-minute survey?


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.

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.

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.

Table 1: Examples and Pseudocode for XSLT Variable Declaration

Variable Declaration

Pseudocode Explanation

<xsl:variable name="mpls" select="protocols/mpls"/>

Assigns the [edit protocols mpls] hierarchy level to the variable named mpls.

<xsl:variable name="color" select="data[name = 'color']/value"/>

Assigns the value of the color macro parameter to a variable named color. The <data> element in the XPath expression is useful in commit script macros. For more information, see Create a Commit Script Macro to Read the Custom Syntax and Generate Related Configuration Statements.