XSLT <xsl:when>
❮ Complete XSLT Element Reference
定義和用法
The <xsl:when> element is used to specify an action for the <xsl:choose> element. The <xsl:when> element evaluates an expression, and if it returns true, an action is performed.
注意: <xsl:when> 元素與 <xsl:choose> 和 <xsl:otherwise> 結合使用,以表達多個條件測試。
語法
<xsl:when
test="boolean-expression">
<!-- Content: template -->
</xsl:when>
屬性
Attribute | 值 | 描述 |
---|---|---|
test | boolean-expression | Required. Specifies a Boolean expression to be tested |
示例 1
下面的程式碼將在 CD 的價格高於 10 時,為 artist 列新增粉色背景色。
<?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">
<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>
檢視 XML 檔案, 檢視 XSL 檔案, and 檢視結果.
示例 2
Declare a variable named "color". Set its value to the color attribute of the current element. If the current element has no color attribute, the value of "color" will be "green"
<xsl:variable name="color">
<xsl:choose>
<xsl:when test="@color">
<xsl:value-of select="@color"/>
</xsl:when>
<xsl:otherwise>green</xsl:otherwise>
</xsl:choose>
</xsl:variable>
❮ Complete XSLT Element Reference