XSLT <choose>

创建于 2024-12-03 / 32
字体: [默认] [大] [更大]

<xsl:choose> 元素与 <xsl:when> 和 <xsl:otherwise> 表示多个条件测试。


<xsl:choose> 元素

语法

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

选择条件的位置

要针对XML文件插入多条件测试,请添加<xsl:choose>, <xsl:when>, and <xsl:otherwise>XSL文件的元素:

实例

<?xml version="1.0" encoding="UTF-8"?>
<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 &gt; 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> 尝试一下 »

当CD的价格高于10时,上面的代码将为"Artist"列添加粉色背景色。



另一个例子

下面是另一个包含两个<xsl:when>要素:

实例

<?xml version="1.0" encoding="UTF-8"?>
<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 &gt; 10">

          <td bgcolor="#ff00ff">
          <xsl:value-of select="artist"/></td>
        </xsl:when>
        <xsl:when test="price &gt; 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> 尝试一下 »

当CD价格高于10时,上面的代码将在"Artist" 列中添加粉色背景色;当CD价格高于9且低于或等于10时,将在"Artist" 列中添加灰色背景色。



0 人点赞过