XSL Transformations
- Feb 23, 2001
Using xsl:choose
The <xsl:choose> element is much like the Java switch statement, which enables you to compare a test value against several possible matches. Suppose that we add COLOR attributes to each <PLANET> element in planets.xml:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xml" href="planets.xsl"?>
<PLANETS>
<PLANET COLOR="RED">
<NAME>Mercury</NAME>
<MASS UNITS="(Earth = 1)">.0553</MASS>
<DAY UNITS="days">58.65</DAY>
<RADIUS UNITS="miles">1516</RADIUS>
<DENSITY UNITS="(Earth = 1)">.983</DENSITY>
<DISTANCE UNITS="million miles">43.4</DISTANCE><!--At perihelion-->
</PLANET>
<PLANET COLOR="WHITE">
<NAME>Venus</NAME>
<MASS UNITS="(Earth = 1)">.815</MASS>
<DAY UNITS="days">116.75</DAY>
<RADIUS UNITS="miles">3716</RADIUS>
<DENSITY UNITS="(Earth = 1)">.943</DENSITY>
<DISTANCE UNITS="million miles">66.8</DISTANCE><!--At perihelion-->
</PLANET>
<PLANET COLOR="BLUE">
<NAME>Earth</NAME>
<MASS UNITS="(Earth = 1)">1</MASS>
<DAY UNITS="days">1</DAY>
<RADIUS UNITS="miles">2107</RADIUS>
<DENSITY UNITS="(Earth = 1)">1</DENSITY>
<DISTANCE UNITS="million miles">128.4</DISTANCE><!--At perihelion-->
</PLANET>
</PLANETS>
Now say that we want to display the names of the various planets, formatted in different ways using HTML <B>, <I>, and <U> tags, depending on the value of the COLOR attribute. I can do this with an <xsl:choose> element. Each case in the <xsl:choose> element is specified with an <xsl:when> element, and you specify the actual test for the case with the test attribute. Heres what it looks like:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="PLANETS">
<HTML>
<HEAD>
<TITLE>
Planets
</TITLE>
</HEAD>
<BODY>
<xsl:apply-templates select="PLANET"/>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="PLANET">
<xsl:choose>
<xsl:when test="@COLOR = RED">
<B>
<xsl:value-of select="NAME"/>
</B>
</xsl:when>
<xsl:when test="@COLOR = WHITE">
<I>
<xsl:value-of select="NAME"/>
</I>
</xsl:when>
<xsl:when test="@COLOR = BLUE">
<U>
<xsl:value-of select="NAME"/>
</U>
</xsl:when>
<xsl:otherwise>
<PRE>
<xsl:value-of select="."/>
</PRE>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Note also the <xsl:otherwise> element in this example, which acts the same way as the default: case in a switch statementthat is, if no other case matches, the <xsl:otherwise> element is applied. Here is the result of this XSLT:
<HTML>
<HEAD>
<TITLE>
Planets
</TITLE>
</HEAD>
<BODY>
<B>Mercury</B>
<I>Venus</I>
<U>Earth</U>
</BODY>
</HTML>