XSLT <xsl:choose> 元素
<xsl:choose> 元素與 <xsl:when> 和 <xsl:otherwise> 結合使用,以表達多個條件測試。
<xsl:choose> 元素
語法
<xsl:choose>
<xsl:when test="表示式">
... 一些輸出 ...
</xsl:when>
<xsl:otherwise>
... 一些輸出 ....
</xsl:otherwise>
</xsl:choose>
選擇條件的位置
要針對 XML 檔案插入多個條件測試,請將 <xsl:choose>、<xsl:when> 和 <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>我的 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>
自己動手試一試 »
上述程式碼將在 CD 價格高於 10 時,為“藝術家”列新增粉色背景。
另一個示例
這是另一個包含兩個 <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>我的 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:when test="price > 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 時,為“藝術家”列新增粉色背景;在 CD 價格高於 9 且低於或等於 10 時,新增灰色背景。