[XML -XSLT] Variables / Parameters

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 :

  • boolean
  • number
  • string
  • node-set
  • 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.

 

4. Boolean

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>

 

5. Numbers

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 &gt; $cost">
  Too Expensive.
</xsl:if>

 

6. Strings

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s