The xsl:variable element is used to declare a local or global variable and to give that variable a name and a value. The value can be assigned by either the content of the xsl:variable element or by the select attribute, but not by both. Each variable declaration requires a separate xsl:variable element. Global variables are declared in the top level of the style sheet (as children of the xsl:stylesheet or xsl:transform elements). Local variables are declared within the template body.
Note that once you set a variable's value, there is no provision in the XSLT language to change or modify that value. This is in sharp contrast to most other computer languages which allow you to repeatedly reassign variable values.
The xsl:param element can also be used to declare parameters. The only real difference between a variable and a parameter is how the value is assigned.
Like all XSLT elements, the xsl:variable element must be closed (well-formed). If the select attribute is present, then this element is self-closing. If the select attribute is not present, then this element is not self-closing and the separate closing element is mandatory.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:variable name="staff_table">
<tr>
<td><b>Name</b></td>
<td><b>Age</b></td>
</tr>
</xsl:variable>
<xsl:template match="/">
<html>
<body>
<table>
<xsl:copy-of select="$staff_table" />
<xsl:for-each select="devguru_staff/programmer">
<tr>
<xsl:if test="age < 35">
<td><xsl:value-of select="name" /></td>
<td><xsl:value-of select="age" /></td>
</xsl:if>
</tr>
</xsl:for-each>
</table>
<p />
<table>
<xsl:copy-of select="$staff_table" />
<xsl:for-each select="devguru_staff/programmer">
<tr>
<xsl:if test="age > 34">
<td><xsl:value-of select="name" /></td>
<td><xsl:value-of select="age" /></td>
</xsl:if>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Name Age
Bugs Bunny
31
Minnie Mouse
24
Pluto
21
Name Age
Daisy Duck
51
Porky Pig
44
Road Runner
48
Here, we create a reuseable table header. This is the code for xslt_example_variable.xsl.
We use the DevGuru Staff List XML file for our example with the following header:
<?xml-stylesheet type="text/xsl" href="xslt_example_variable.xsl"?>