Skip to content

XSLT <xsl:when>

How to use the <xsl:when> element in XSLT to evaluate conditional expressions within <xsl:choose> and implement branch logic for XML transformations.

XSLT <xsl:when>

The <xsl:when> element is used to specify an action for the <xsl:choose> element. The <xsl:when> element evaluates an expression, and if it returns true, an action is performed.

Syntax

<xsl:when test="boolean-expression">  
	<!-- Content: template -->  
</xsl:when>

Attributes

Attribute Value Required/Optional Description
test boolean-expression Required Specifies a Boolean expression to be tested

Example

Let's see some examples:

Example 1

The code below will add a red background-color to the author column when the price of the book is higher than 15.

<?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="#9acd32">
        <th>Title</th>
        <th>Author</th>
      </tr>
      <xsl:for-each select="bookstore/book">
      <tr>
        <td><xsl:value-of select="title"/></td>
        <xsl:choose>
          <xsl:when test="price&gt;'15'">
            <td bgcolor="#ff0000">
            <xsl:value-of select="author"/></td>
          </xsl:when>
          <xsl:otherwise>
            <td><xsl:value-of select="author"/></td>
          </xsl:otherwise>
        </xsl:choose>
      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>

Example 2

Declare a variable named "color". Set its value to the color attribute of the current element. If the current element has no color attribute, the value of "color" will be "red":

<xsl:variable name="color">
  <xsl:choose>
    <xsl:when test="@color">
      <xsl:value-of select="@color"/>
    </xsl:when>
    <xsl:otherwise>red</xsl:otherwise>
  </xsl:choose>
</xsl:variable>
Navigation