XSLT <xsl:if> 元素
定義和用法
<xsl:if> 包含了一個模板,只有指定的條件成立時,才應用此模板。
提示:請使用 <xsl:choose> 與 <xsl:when> 和 <xsl:otherwise> 結合,來表達多重條件測試!
語法
<xsl:if test="expression"> <!-- Content: template --> </xsl:if>
屬性
屬性 | 值 | 描述 |
---|---|---|
test | expression | 必需。規定要測試的條件。 |
實例
例子 1
當 CD 的價格高于 10 時,選取 title 和 artist 的值:
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</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>
查看 XML 文件,查看 XSL 文件,查看結果。
例子 2
顯示每個 CD 的標題。如果不是最后一個或倒數第二個 CD,則在每個 CD-title 間插入 ", "。如果是最后一個 CD,則在標題后添加 "!"。如果是倒數第二個 CD,則在其后添加 ", and ":
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <p>Titles: <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 <xsl:apply-templates> 元素 下一篇: XSLT <xsl:comment> 元素