Thẻ <xsl:choose> XSLT

Điều khiển XSLT <xsl:choose> được sử dụng để kết hợp <xsl:when> và <xsl:otherwise> để biểu đạt các điều kiện kiểm tra đa điều kiện.

<xsl:choose> phần tử

cú pháp

<xsl:choose>
  <xsl:when test="bày tỏ">
    ... đầu ra ...
  </xsl:when>
  <xsl:otherwise>
    ... đầu ra ...
  </xsl:otherwise>
</xsl:choose>

Đ放置 điều kiện chọn

Để chèn các điều kiện kiểm tra đa điều kiện cho tệp XML, hãy thêm <xsl:choose>, <xsl:when> và <xsl:otherwise> vào tệp XSL:

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

Mã trên sẽ thêm màu nền hồng cho cột "Artist" khi giá CD cao hơn 10.

Kết quả chuyển đổi trên sẽ tương tự như vậy:

Xem tệp XML này,Xem tệp XSL này,Xem kết quả.

Một ví dụ khác

Đây là một ví dụ khác chứa hai phần tử <xsl:when>:

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

Mã trên sẽ thêm màu nền hồng vào cột "Artist" khi giá CD cao hơn 10, và thêm màu nền xám vào cột "Artist" khi giá CD cao hơn 9 và nhỏ hơn hoặc bằng 10.

Kết quả chuyển đổi trên sẽ tương tự như vậy:

Xem tệp XML này,Xem tệp XSL này,Xem kết quả.