Skip to main content

XSLT <xsl:choose> Element

The <xsl:choose> element is used in conjunction with <xsl:when> and <xsl:otherwise> to express multiple conditional tests.

<xsl:choose> Element

Syntax

The syntax of <xsl:choose> is as follows:

<xsl:choose >
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>

Example

Let's see an example:

books.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>

<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Tips</title>
<author>Tom Nolan</author>
<year>2022</year>
<price>39.99</price>
</book>
<book category="web">
<title lang="en">Learn XML</title>
<author>Tutorial Reference</author>
<year>2022</year>
<price>9.99</price>
</book>
</bookstore>
books.xsl
<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>The Bookstore</h2>
<table border="1">
<tr bgcolor="#6565d5">
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Price</th>
<th>Before 2000</th>
</tr>
<xsl:for-each select="bookstore/book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="year"/></td>
<td><xsl:value-of select="price"/></td>
<td>
<xsl:choose>
<xsl:when test="year &lt; 2000">Yes</xsl:when>
<xsl:otherwise> No </xsl:otherwise>
</xsl:choose>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>
note

In the example, the "Before 2000" column has value "Yes" when the year of the book is before 2000, "No" otherwise.

note

You can declare multiple <xsl:when> element.

For example:

<xsl:choose> 
<xsl:when test="temperature > 90"> High </xsl:when>
<xsl:when test="temperature > 50"> Medium </xsl:when>
<xsl:otherwise> Low </xsl:otherwise>
</xsl:choose>