O'Reilly logo

Java and XSLT by Eric M. Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Parameters and Variables

As in other programming languages, it is often desirable to set up a variable whose value is reused in several places throughout a stylesheet. If the title of a book is displayed repeatedly, then it makes sense to store that title in a variable rather than scan through the XML data and locate the title repeatedly. It can also be beneficial to set up a variable once and pass it as a parameter to one or more templates. These templates often use <xsl:if> or <xsl:choose> to produce different content depending on the value of the parameter that was passed.

<xsl:variable>

Variables in XSLT are defined with the <xsl:variable> element and can be global or local. A global variable is defined at the “top-level” of a stylesheet, which means that it is defined outside of any templates as a direct child of the <xsl:stylesheet> element. Top-level variables are visible throughout the entire stylesheet, even in templates that occur before the variable declaration.

The other place to define a variable is inside of a template. These variables are visible only to elements that follow the <xsl:variable> declaration within that template and to their descendants. The code in Example 3-2 showed this form of <xsl:variable> as a mechanism to define the font color.

Defining variables

Variables can be defined in one of three ways:

<xsl:variable name="homePage">index.html</xsl:variable> <xsl:variable name="lastPresident"select="president[position() = last( )]/name"/> <xsl:variable ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required