XSLT is more than just simple one-to-one transformation between two documents. You can create rules just like you are using programming languages.
1. Creating Variables
A variable is a named container for a value that can be referenced. <xsl:variable> element is used to create a variable.
Each <xsl:variable> element usually has two attributes :
- name : specifies the name of variable
- select : holds an expression that specifies the value of the variable.
<xsl:variable name="daysInYear" select="365" /> <xsl:variable name="country" select="'Canada'" />
There are five types of values that a variable can hold :
- result tree fragment
2. Referring to variables
A variable is accessed by referring to its name with a ‘$‘ prefix.
<xsl:variable name="compared-age" select="30" /> <xsl:if test="@age = $compared-age"> ... </xsl:if>
<xsl:value-of> element can be used to insert a variable value inside the text string.
Age : <xsl:value-of select="$compared-age" />
3. XSLT variables are NOT variables?
XSLT variables have one peculiar feature : they can’t vary. Once the value of a local variable is set, it remains the same throughout its scope.
A variable is assigned to the boolean data type using the XPath true() and false() functions.
<xsl:variable name="on" select="true()" /> <xsl:variable name="off" select="false()" />
A boolean variable can be used in debugging codes.
<xsl:variable name="debug" select="true()" /> <xsl:if test="$debug"> .... </xsl:if>
An expression can be a simple number or a calculation that results in a number.
<xsl:variable name="age" select="20" /> <xsl:variable name="age" select="18+2" />
A numeric variable can be used in calculations and comparisons.
<xsl:variable name="cost" select="20" /> <xsl:if test="item/cost > $cost"> Too Expensive. </xsl:if>
A string identified using quotation marks around the characters that constitute the value. These quotation marks must not be the same kind as those used to enclose the select attribute value. For example, select=”book” assigns a node set of <book> element to the variable, whereas select=” ‘book’ ” assigns the string ‘book’ to the variable.
<xsl:variable name="stop" select=" 'color:red' " /> <xsl:variable name="ok" select=" 'color:green' " />
7. Node Sets
When the select attribute contains a location path, the variable becomes a reference to the node selected by this expression.