magnify-glassThe XSLT <xsl:variable> element binds a value to a name, much like you would expect in any programming language.

XSLT variables can be either be global or local in scope. If the variable is declared as a top-level element to the stylesheet then the variable’s scope is global. Otherwise the variable is within the local scope of the declaring template.

XSLT variables are more like named constants: They cannot be changed once they are set.

XSLT variables can be referenced using the form “$name” from a relevant XSL declaration.



<xsl:variable name="name" select="expression" />


<xsl:variable name="name">
content goes here


nameREQUIRED. Specifies the variable name. The name must be unique within the declaring scope.
selectOPTIONAL. Specifies an XPATH expression that defines the variable content. The variable content type is determined by the return-type of the expression. This includes literal expressions as well.


Default Values

If the variable is defined with only a name; and no select or content, then the variable defaults to an empty string. This example is the no-value equivalent of the content template value example.

<xsl:variable name="name" />

Expression Values

The select attribute contains any XPATH expression that results in a value.

Literal values can be defined as a string values enclosed in quotes. This is otherwise known as a constant.

<xsl:variable name="name" select"'literal value'" />

XPATH expressions NOT enclosed in quotes are evaluated against the source XML document:

<xsl:variable name="name" select="/*/category/@name" />

Content Template Values

xsl:variables can define the variable content as either static or generated values. The example shows an example where both are combined: One book is hardcoded, the second books’ title is built from XPATH expressions.

<xsl:variable name="">
<book title="my static name" />
<xsl:attribute name="title"><xsl:value-of select="/*/category/@name" /></xsl:attribute>

Select Variable

To select, work with or otherwise manipulate a variable, select the variable by its name

… select =”$name” …

<result>The value of the variable is '<xsl:value-of select="$name" />' and is processed...</result>

Template Return Values

A useful technique is to set the variable equal to the results of another template. This allows you to reuse the results of the template without the need to invoke it again.

<xsl:variable name="name">
<xsl:call-template name="myCustomTemplate" />

Node Variable Values

A node can also be defined as a variable value.

<xsl:variable name="name" select="/category/book[@title='All about dogs']" />

The book price is: <xsl:value-of select="$name/price" />

Constant Values

Define a constant by specifying a literal value as the variables’ value.

<xsl:variable name="name" select"'literal value'" />

Posted in XSLT and tagged .

Leave a Reply