XSL 也能寫條件判斷——寫起來還真有幾分程式語言的味道。
做法是加入一個 xsl:if 元素,語法大致如下:
<xsl:if match=".[ARTIST='Bob Dylan']">
... 要輸出的內容 ...
</xsl:if>
把它放進先前的 CD 目錄範例,只列出 Bob Dylan 的專輯:
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="https://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<html>
<body>
<table border="2" bgcolor="yellow">
<tr>
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="CATALOG/CD">
<xsl:if match=".[ARTIST='Bob Dylan']">
<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>
這裡的判斷是「有條件才輸出」,沒有 else 分支。也就是說,if 只處理單一路徑的情況。
如果需要在多個條件之間給出不同的呈現結果,就輪到 xsl:choose 上場。它由一組 xsl:choose、xsl:when、xsl:otherwise 元素組成,概念等同於 if / else if / else:
<xsl:choose>
<xsl:when match=".[ARTIST='Bob Dylan']">
... 條件成立時的程式碼 ...
</xsl:when>
<xsl:otherwise>
... 其他情況的程式碼 ...
</xsl:otherwise>
</xsl:choose>
改寫後的完整範例如下,這次條件不成立時也會輸出,只是樣式不同:
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="https://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<html>
<body>
<table border="2" bgcolor="yellow">
<tr>
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="CATALOG/CD">
<tr>
<td><xsl:value-of select="TITLE"/></td>
<xsl:choose>
<xsl:when match=".[ARTIST='Bob Dylan']">
<td bgcolor="#ff0000"><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>
效果很直觀:符合條件的藝人名稱會以紅底呈現,其餘維持一般樣式。若要在多個 xsl:when 之間挑選,只要往下增加分支即可,第一個成立的條件會優先被採用。