Element <xsl:choose> XSLT

Element <xsl:choose> w XSLT służy do łączenia <xsl:when> i <xsl:otherwise>, aby wyrazić wielokrotne testy warunkowe.

<xsl:choose> element

Syntax

<xsl:choose>
  <xsl:when test="expression">
    ... Output ...
  </xsl:when>
  <xsl:otherwise>
    ... Output ...
  </xsl:otherwise>
</xsl:choose>

Where to place the selection condition

To insert multiple conditional tests for the XML file, add <xsl:choose>, <xsl:when>, and <xsl:otherwise> to the XSL file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for-each select="catalog/cd">
      <tr>
        <td><xsl:value-of select="title"/></td>
      	<xsl:choose>
          <xsl:when test="price > 10">
            <td bgcolor="#ff00ff">
            <xsl:value-of select="artist"/></td>
          </xsl:when>
          <xsl:otherwise>
            <td><xsl:value-of select="artist"/></td>
          </xsl:otherwise>
        </xsl:choose>
      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

The above code will add a pink background color to the "Artist" column when the CD price is higher than 10.

Powyższy wynik konwersji wygląda podobnie:

View this XML file,View this XSL file,Zobacz wynik.

Another example

To another example that includes two <xsl:when> elements:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
<xsl:template match="/">
  <html>
  <body>
    <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for-each select="catalog/cd">
      <tr>
        <td><xsl:value-of select="title"/></td>
      	<xsl:choose>
          <xsl:when test="price > 10">
            <td bgcolor="#ff00ff">
            <xsl:value-of select="artist"/></td>
          </xsl:when>
          <xsl:when test="price > 9">
            <td bgcolor="#cccccc">
            <xsl:value-of select="artist"/></td>
          </xsl:when>
          <xsl:otherwise>
            <td><xsl:value-of select="artist"/></td>
          </xsl:otherwise>
        </xsl:choose>
      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Powyższy kod doda różowy kolor tła do kolumny "Artist", gdy cena CD będzie wyższa niż 10, oraz doda szary kolor tła do kolumny "Artist", gdy cena CD będzie wyższa niż 9 i mniejsza lub równa 10.

Powyższy wynik konwersji wygląda podobnie:

Zobacz ten plik XML,Zobacz ten plik XSL,Zobacz wynik.