XSLT <xsl:if> 元素
定义和用法
<xsl:if> 包含了一个模板,只有指定的条件成立时,才应用此模板。
提示:请使用 <xsl:choose> 与 <xsl:when> 和 <xsl:otherwise> 结合,来表达多重条件测试!
语法
<xsl:if test="expression"> <!-- Content: template --> </xsl:if>
属性
| 属性 | 值 | 描述 | 
|---|---|---|
| test | expression | 必需。规定要测试的条件。 | 
实例
例子 1
当 CD 的价格高于 10 时,选取 title 和 artist 的值:
<?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">
      <xsl:if test="price > 10">
        <tr>
          <td><xsl:value-of select="title"/></td>
          <td><xsl:value-of select="artist"/></td>
        </tr>
      </xsl:if>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>
例子 2
显示每个 CD 的标题。如果不是最后一个或倒数第二个 CD,则在每个 CD-title 间插入 ", "。如果是最后一个 CD,则在标题后添加 "!"。如果是倒数第二个 CD,则在其后添加 ", and ":
<?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>
    <p>Titles:
    <xsl:for-each select="catalog/cd">
      <xsl:value-of select="title"/>
      <xsl:if test="position()!=last()">
        <xsl:text>, </xsl:text>
      </xsl:if>
      <xsl:if test="position()=last()-1">
        <xsl:text> and </xsl:text>
      </xsl:if>
      <xsl:if test="position()=last()">
        <xsl:text>!</xsl:text>
      </xsl:if>
    </xsl:for-each>
    </p>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>