XSLT <xsl:choose> Element
- Previous Page XSLT <if>
- Next Page XSLT Apply
The XSLT <xsl:choose> element is used to combine <xsl:when> and <xsl:otherwise> to express multiple conditional tests.
<xsl:choose> element
Syntax
<xsl:choose> <xsl:when test="expression"> ... output ... </xsl:when> <xsl:otherwise> ... output ... </xsl:otherwise> </xsl:choose>
Where to place the selection condition
To insert multiple conditional tests for an XML file, add <xsl:choose>, <xsl:when>, and <xsl:otherwise> to the XSL file:
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="title"/></td> <xsl:choose> <xsl:when test="price > 10"> <td bgcolor="#ff00ff"> <xsl:value-of select="artist"/></td> </xsl:when> <xsl:otherwise> <td><xsl:value-of select="artist"/></td> </xsl:otherwise> </xsl:choose> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>
The above code will add a pink background color to the "Artist" column when the CD price is higher than 10.
The conversion result is similar to this:

Another example
This is another example containing two <xsl:when> elements:
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="title"/></td> <xsl:choose> <xsl:when test="price > 10"> <td bgcolor="#ff00ff"> <xsl:value-of select="artist"/></td> </xsl:when> <xsl:when test="price > 9"> <td bgcolor="#cccccc"> <xsl:value-of select="artist"/></td> </xsl:when> <xsl:otherwise> <td><xsl:value-of select="artist"/></td> </xsl:otherwise> </xsl:choose> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>
The above code will add a pink background color to the "Artist" column when the price of the CD is higher than 10, and add a gray background color to the "Artist" column when the price of the CD is higher than 9 and less than or equal to 10.
The conversion result is similar to this:

- Previous Page XSLT <if>
- Next Page XSLT Apply