XSLT Variables

Contact Us or call 1-877-932-8228
XSLT Variables

XSLT Variables

Variables in XSLT are similar to constants in other programming languages; there is no way to change their values once they have been set. They are often used to store complex XPaths or values that will be used repeatedly. We'll illustrate with an example.

Code Sample:

TemplatesParametersVariables/Demos/BeatlesVariables.xml
<?xml version="1.0"?>
<?xml-stylesheet href="BeatlesVariables.xsl" type="text/xsl"?>
<beatles>
	<beatle link="http://www.paulmccartney.com">
		<name>
			<firstname>Paul</firstname>
			<lastname>McCartney</lastname>
		</name>
	</beatle>
	<beatle link="http://www.johnlennon.com">
		<name>
			<firstname>John</firstname>
			<lastname>Lennon</lastname>
		</name>
	</beatle>
	<beatle link="http://www.georgeharrison.com">
		<name>
			<firstname>George</firstname>
			<lastname>Harrison</lastname>
		</name>
	</beatle>
	<beatle link="http://www.ringostarr.com">
		<name>
			<firstname>Ringo</firstname>
			<lastname>Starr</lastname>
		</name>
	</beatle>
</beatles>

Code Sample:

TemplatesParametersVariables/Demos/BeatlesVariables.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" 
				xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="xml" indent="yes"/>
	<xsl:variable name="lc">abcdefghijklmnopqrstuvwxyz</xsl:variable>
	<xsl:variable name="uc">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>
	<xsl:variable name="Band" 
		select="translate(name(/*[1]),$lc,$uc)"/>
	<xsl:template match="/">
		<html>
			<head>
				<title><xsl:value-of select="$Band"/></title>
			</head>
			<body>
				<h1 align="center"><xsl:value-of select="$Band"/></h1>
				<ul>
					<xsl:for-each select="//beatle">
						<li>
							<xsl:value-of select="name/firstname"/>
							<xsl:text> </xsl:text>
							<xsl:value-of select="name/lastname"/>
						</li>
					</xsl:for-each>
				</ul>
			</body>
		</html>
	</xsl:template>
</xsl:stylesheet>

As shown above, variables are created with the xsl:variable tag. The name of the variable is specified by the name attribute and the value can either be specified in the select attribute or between the open and close xsl:variable tags. The result of transforming TemplatesParametersVariables/Demos/BeatlesVariables.xml against TemplatesParametersVariables/Demos/BeatlesVariables.xsl is shown below.

Code Sample:

TemplatesParametersVariables/Demos/BeatlesVariablesOutput.html
<?xml version="1.0" encoding="UTF-8"?>
<html>
	<head>
		<title>BEATLES</title>
	</head>
	<body>
		<h1 align="center">BEATLES</h1>
		<ul>
			<li>Paul McCartney</li>
			<li>John Lennon</li>
			<li>George Harrison</li>
			<li>Ringo Starr</li>
		</ul>
	</body>
</html>
Next