XSLT <xsl:if>
❮ XSLT 元素参考
定义和用法
The <xsl:if> 元素包含一个模板,仅当指定的条件为真时才应用该模板。
提示: 将 <xsl:choose> 与 <xsl:when> 和 <xsl:otherwise> 结合使用,可以表达多个条件测试!
语法
<xsl:if
test="expression">
<!-- Content: template -->
</xsl:if>
属性
Attribute | 值 | 描述 |
---|---|---|
test | expression | 必需。指定要测试的条件 |
示例
如果 CD 的价格高于 10,则选择标题和艺术家的值
示例 1
<?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>我的 CD 收藏</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>标题</th>
<th>艺术家</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>
自己动手试一试 »
显示每个 CD 的标题。如果在最后一张 CD 或倒数第二张 CD 之前,则在每张 CD 标题之间插入“, ”。如果它是最后一张 CD,则在标题后添加“!”。如果它是倒数第二张 CD,则在标题后添加“, and ”
示例 2
<?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>我的 CD 收藏</h2>
<p>标题
<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>
自己动手试一试 »
❮ XSLT 元素参考