Variables
If we use logic to control the flow of our stylesheets,
we’ll probably want to store temporary results along the way. In other
words, we’ll need to use variables. XSLT provides the <xsl:variable>
element, which allows you to store a value and associate it with
a name.
The <xsl:variable>
element can be used in three ways. The simplest form of the element
creates a new variable whose value is an empty string (""
). Here’s how it looks:
<xsl:variable name="x"/>
This element creates a new variable named x
, whose value is an empty string. (Please
hold your applause until the end of the section.)
You can also create a variable by adding a select
attribute to the <xsl:variable>
element:
<xsl:variable name="favouriteColour" select="'blue'"/>
In this case, we’ve set the value of the variable to be the string
“blue”. Notice that we put single quotes around the value. These quotes
ensure that the literal value blue
is
used as the value of the variable. If we had left out the single quotes,
this would mean the value of the variable is the node-set (or sequence)
of all the <blue>
elements in
the context node, which definitely isn’t what we want here.
Warning
Be aware that single quotes around numeric values are significant. The value 35
represents a numeric value (it’s a number
in XSLT 1.0, and an xs:integer
in
XSLT 2.0), while the value '35'
represents the string 35
. That might seem like a minor
distinction, but it has a major impact on how your stylesheet works,
especially in XSLT 2.0.
The ...
Get XSLT, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.