[2.0] Conditional Expressions—if, then, and else

One of the less elegant features of XSLT is its if-then-else logic. If I want to test one condition (a simple if), I use <xsl:if>. If I want to change that to test more than one condition or add an else case, I have to use <xsl:choose>, <xsl:when>, and <xsl:otherwise>. (We cover those elements in Chapter 5.) XPath 2.0 gives us the extremely useful if operator. We can now do if-then-else logic inside the XPath expression itself.

For comparison, here’s how we do things in XSLT 1.0:

<?xml version="1.0"?>
<!-- if-1_0.xsl -->
<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:param name="x" select="'10'"/>

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:text>&#xA;An example of if-then-else logic in XSLT 1.0:</xsl:text>
    <xsl:text>&#xA;&#xA;  If $x is larger than 10, print 'Big', </xsl:text>
    <xsl:text>&#xA;    otherwise print 'Little'</xsl:text>
    <xsl:text>&#xA;&#xA;           </xsl:text>
    <xsl:choose>
      <xsl:when test="$x &gt; 10">
        <xsl:text>Big</xsl:text>
      </xsl:when>
      <xsl:otherwise>
        <xsl:text>Little</xsl:text>
      </xsl:otherwise>
    </xsl:choose>
    <xsl:text>&#xA;</xsl:text>
  </xsl:template>

</xsl:stylesheet>

We look at the value of $x and write Big if it’s larger than 10; otherwise, we write Little. Pretty simple stuff, but the <xsl:choose> element takes up 8 lines here. To do the same thing in XSLT 2.0, it’s much simpler:

<?xml version="1.0"?>
<!-- if-2_0.xsl --> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.