XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – round two / Conditions with XSLT and XPath / More decisions in XSLT: xsl:choose

(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 2.)

Another way to decide whether a template section runs within a stylesheet is xsl:choose. More precisely, xsl:choose is only a container for the actual condition tested with instruction xsl:when. An optional ELSE branch can be expressed with instruction xsl:otherwise.

Using, inside xsl:choose, exactly one xsl:when together with xsl:otherwise gives an exact equivalent of IF-ELSE. The principle is:

<xsl:choose>
  <xsl:when test="falls das hier wahr ist">
    ... tu dies ...
  </xsl:when> 
  <xsl:otherwise>
    ... ansonsten tu dies hier ...
  </xsl:otherwise>
</xsl:choose>

The outer xsl:choose has no attributes, nor does the xsl:otherwise at the end of the block. The latter runs automatically when the preceding when test fails. You can also omit xsl:otherwise if you do not want a default instruction. The effect then exactly matches instruction xsl:if:

<xsl:choose>
  <xsl:when test="falls das hier wahr ist">
    ... tu dies ...
  </xsl:when> 
</xsl:choose>

is therefore equivalent to:

<xsl:if test="falls das hier wahr ist">
  ... tu dies ...
</xsl:if>

When designing a stylesheet, note that although the first expression is more verbose, it is extensible. An ELSE branch can be added without changing the instruction.

There are further differences. The xsl:choose container can contain several xsl:when instructions in sequence, but always at most one xsl:otherwise at the end of the block. This allows structures resembling SELECT or switch statements:

<xsl:choose>
  <xsl:when test="falls das hier wahr ist">
    ... tu dies ...
  </xsl:when> 
  <xsl:when test="falls aber das hier wahr ist">
    ... tu jenes ...
  </xsl:when> 
  <!-- optionaler Default-Block: -->
  <xsl:otherwise>
    ... ansonsten tu dies hier ...
  </xsl:otherwise>
</xsl:choose>

Any number of xsl:when instructions can be chained; only the first whose test succeeds runs. Subsequent xsl:when instructions are ignored even if their conditions would be true.

Several consecutive xsl:if are therefore not equivalent to several xsl:when in xsl:otherwise, since their tests are independent. In that case, every xsl:if whose test succeeds would run.

Using xsl:choose improves the ISBN note and can display a note when no ISBN exists. The condition used for xsl:if, here the extended condition, can simply be reused for xsl:when:

<xsl:template match="buch">
  <p>
    <xsl:apply-templa¬tes/>
    <xsl:choose>
      <xsl:when test="@isbn != ''">
        <br/>(ISBN: <xsl:value-of select="@isbn"/>)
      </xsl:when>
      <xsl:otherwise>
        <br/>(ISBN-Nummer liegt nicht vor.)
      </xsl:otherwise>
    </xsl:choose>
  </p>
</xsl:template>

Code example: kap02/2.02.2/buchhandel-choose1.xsl (excerpt).

  

back to top