XSLT - What are <xsl:choose>, <xsl:when>, and <xsl:otherwise>?

What are <xsl:choose>, <xsl:when>, and <xsl:otherwise>?

They work like an if–elseif–else structure in other programming languages.

  • <xsl:choose> → container for conditional statements.

  • <xsl:when> → like an if or elseif. You can have multiple.

  • <xsl:otherwise> → like an else (optional, only one allowed).


Syntax

<xsl:choose>
    <xsl:when test="condition1">
        <!-- Executes if condition1 is true -->
    </xsl:when>
    <xsl:when test="condition2">
        <!-- Executes if condition2 is true -->
    </xsl:when>
    <xsl:otherwise>
        <!-- Executes if no condition is true -->
    </xsl:otherwise>
</xsl:choose>

Example XML

<students>
    <student>
        <name>John</name>
        <marks>85</marks>
    </student>
    <student>
        <name>Sara</name>
        <marks>45</marks>
    </student>
    <student>
        <name>Mike</name>
        <marks>60</marks>
    </student>
</students>

XSLT with <xsl:choose>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">
        <html>
            <body>
                <h2>Student Results</h2>
                <ul>
                    <xsl:for-each select="students/student">
                        <li>
                            <xsl:value-of select="name"/> - 
                            <xsl:choose>
                                <xsl:when test="marks &gt;= 75">Distinction</xsl:when>
                                <xsl:when test="marks &gt;= 50">Pass</xsl:when>
                                <xsl:otherwise>Fail</xsl:otherwise>
                            </xsl:choose>
                        </li>
                    </xsl:for-each>
                </ul>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

Output (HTML)

<html>
  <body>
    <h2>Student Results</h2>
    <ul>
      <li>John - Distinction</li>
      <li>Sara - Fail</li>
      <li>Mike - Pass</li>
    </ul>
  </body>
</html>

 This is how you handle conditional branching in XSLT.

 

Would you like me to also show you how to use <xsl:if> (simpler than <xsl:choose>) for single-condition checks, so you can compare?