XSLT <xsl:choose> Element

Das XSLT <xsl:choose>-Element wird verwendet, um <xsl:when> und <xsl:otherwise> zu kombinieren, um mehrfache Bedingungen zu testen.

<xsl:choose> Element

Syntax

<xsl:choose>
  <xsl:when test="Ausdruck">
    ... Ausgabe ...
  </xsl:when>
  <xsl:otherwise>
    ... Ausgabe ...
  </xsl:otherwise>
</xsl:choose>

Wo die Auswahlbedingungen platziert werden

Um mehrfache Bedingungen in einer XML-Datei zu testen, fügen Sie <xsl:choose>, <xsl:when> und <xsl:otherwise> zur XSL-Datei hinzu:

<?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>

Der obige Code fügt der "Artist"-Spalte eine rosa Hintergrundfarbe hinzu, wenn der Preis des CDs höher als 10 ist.

The above conversion result is similar to this:

Betrachten Sie diese XML-Datei,Betrachten Sie diese XSL-Datei,View Results.

Ein weiteres Beispiel

Dies ist ein weiteres Beispiel mit zwei <xsl:when>-Elementen:

<?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>

The above code will add a pink background color to the "Artist" column when the CD price is higher than 10, and add a gray background color to the "Artist" column when the CD price is higher than 9 and less than or equal to 10.

The above conversion result is similar to this:

View this XML file,View this XSL file,View Results.