Choose Element: <xsl:choose>

When you would like to use multiple condition within XSLT transformation, you can use <xsl:choose> element. When you use this element, it is necessary to use two tests <xsl:when> and <xsl:otherwise>

Syntax:

<xsl:choose>
<xsl:when test="EXPRESSION">
    --- Your Html part here ---
</xsl:when>
<xsl:otherwise>
    --- Your Html part here ---
</xsl:otherwise>
</xsl:choose>

Let’s use following example to learn more about it.

XML:

<?xml version="1.0" encoding="UTF-8"?>
<products>
  <product>
    <name>Sony Xperia R1 Dual</name>
    <color>Silver</color>
    <price>$650.00</price>
    <discount>0</discount>
  </product>
  <product>
    <name>Sony Large P1</name>
    <color>White</color>
    <price>$750.00</price>
    <discount>30.00</discount>
  </product>
  <product>
    <name>Sony Xperia XP1</name>
    <color>Gold</color>
    <price>$850.00</price>
    <discount>0</discount>
  </product>
  <product>
    <name>Sony Xperia XP1 Latest 2018</name>
    <color>Black</color>
    <price>$950.00</price>
    <discount>50.00</discount>
  </product>
</products>

XSLT:

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<span style="font-size:25px; font-weight:bold;">Products </span>
<table cellpadding="5" cellspacing="5" border="1" style="border:solid 1px silver;">
  <tr bgcolor="silver">
    <th>Name</th>
    <th>Color</th>
    <th>Price</th>
    <th>Discount</th>
  </tr>
  <xsl:for-each select="products/product[color=’Silver’]">
  <tr>
    <td> <xsl:value-of select="name"/> </td>
    <td> <xsl:value-of select="color"/> </td>
    <td> <xsl:value-of select="price"/> </td>
    <xsl:choose>
    <xsl:when test="discount>0">
    <td bgcolor="green"> <xsl:value-of select="discount"/> </td>
    </xsl:when>
    <xsl:choose>
    <xsl:otherwise>
      <td bgcolor="red">N/A </td>
    </xsl:otherwise>
    </xsl:choose>
  </tr>
  </xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Output:

In above example, we can see green color as background that has discount greater than 0 other wise it set background red with text “N/A” in cell. So here, we used multiple text conditions by using choose with when and otherwise elements.