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 元素參考