xml
  1. xml-xsl-choose

XML xsl:choose

  • The xsl:choose element in XSLT is used to create conditional processing.
  • It is often used in conjunction with xsl:when and xsl:otherwise elements.

Syntax

<xsl:choose>
   <xsl:when test="expression"> <!-- processing1 --> </xsl:when>
   <xsl:when test="expression"> <!-- processing2 --> </xsl:when>
   <xsl:otherwise> <!-- processing3 --> </xsl:otherwise>
</xsl:choose>

Example

Let's consider an example where we need to display a message based on the grade of a student. If the grade is above 90, we need to display "Excellent", if the grade is above 75, we need to display "Good", else we need to display "Needs improvement".

<xsl:choose>
   <xsl:when test="grade > 90"> Excellent </xsl:when>
   <xsl:when test="grade > 75"> Good </xsl:when>
   <xsl:otherwise> Needs improvement </xsl:otherwise>
</xsl:choose>

Output

The output of the above example for a student with grade 80 will be "Good".

Explanation

  • The xsl:choose element is used to create conditional processing in XSLT.
  • The xsl:when element is used to define a condition. If the condition is true, then the processing defined inside the xsl:when element will be executed.
  • The xsl:otherwise element is used to define the processing that will be executed if none of the conditions defined inside the xsl:when elements are true.

Use

The xsl:choose element is used when we need to perform conditional processing based on multiple conditions.

Important Points

  • The xsl:choose element must contain atleast one xsl:when element.
  • The xsl:otherwise element is optional and should be placed at the end of the xsl:choose element.
  • If none of the conditions inside xsl:when elements are true, the processing defined inside xsl:otherwise element will be executed.

Summary

In summary, the xsl:choose element in XSLT is used to create conditional processing and is often used in conjunction with xsl:when and xsl:otherwise elements. It is used when we need to perform conditional processing based on multiple conditions.

Published on: