XSL 同樣具備條件判斷能力(呵呵,很厲害吧,簡直跟程式語言一樣)。以下分兩部分說明。
具體做法是增加一個 xsl:if 元素,語法類似這樣:
<xsl:if match=".[ARTIST='Bob Dylan']"> ... some output ... </xsl:if>
把它套進完整的範例改寫如下:
<?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>
這段寫法的效果是:迴圈走訪每一張 CD,只有 ARTIST 為 Bob Dylan 的那些才會被輸出到表格裡。
choose 的用途是:當存在多個可能條件時,給出不同的顯示結果。具體做法是增加一組 xsl:choose、xsl:when、xsl:otherwise 元素:
<xsl:choose> <xsl:when match=".[ARTIST='Bob Dylan']"> ... some code ... </xsl:when> <xsl:otherwise> ... some code .... </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>
這裡的效果是:符合條件的 CD 其演出者欄位會以紅色底 highlighted 呈現,其餘則維持一般樣式。實務上,if 適合處理單一條件的過濾,choose 則適合需要多個分支、且各分支輸出不同的場合;兩者也可以在 for-each 迴圈內自由搭配使用。