A variable-binding element can specify the value of the variable in
three alternative ways.
-
If the variable-binding element has a select
attribute, then the value of the attribute must be an Expression and the value of the variable
is the object that results from evaluating the expression. In this
case, the content must be empty.
-
If the variable-binding element does not have a select
attribute and has non-empty content (i.e. the variable-binding element
has one or more child nodes), then the content of the
variable-binding element specifies the value. The content of the
variable-binding element is a template, which is instantiated to give
the value of the variable. The value is a result tree fragment
equivalent to a node-set containing just a single root node having as
children the sequence of nodes produced by instantiating the template.
The base URI of the nodes in the result tree fragment is the base URI
of the variable-binding element.
It is an error if a member of the sequence of nodes created by
instantiating the template is an attribute node or a namespace node,
since a root node cannot have an attribute node or a namespace node as
a child. An XSLT processor may signal the error; if it does not signal
the error, it must recover by not adding the attribute node or
namespace node.
-
If the variable-binding element has empty content and does not have
a select attribute, then the value of the variable is an
empty string. Thus
<xsl:variable name="x"/>
is equivalent to
<xsl:variable name="x" select="''"/>
NOTE:
When a variable is used to select nodes by position, be careful
not to do:
<xsl:variable name="n">2</xsl:variable>
...
<xsl:value-of select="item[$n]"/>
This will output the value of the first item element, because the
variable n will be bound to a result tree fragment, not a
number. Instead, do either
<xsl:variable name="n" select="2"/>
...
<xsl:value-of select="item[$n]"/>
or
<xsl:variable name="n">2</xsl:variable>
...
<xsl:value-of select="item[position()=$n]"/>