XSLT <xsl:if> Element
Definition and usage
The <xsl:if> element contains a template that is applied only when the specified condition is true.
Hint: Use <xsl:choose> with <xsl:when> and <xsl:otherwise> to express multiple conditional tests!
Syntax
<xsl:if test="expression"> <!-- Content: template --> </xsl:if>
Attribute
Attribute | Value | Description |
---|---|---|
test | expression | Required. Specifies the condition to be tested. |
Instance
Example 1
When the price of the CD is higher than 10, select the values of title and 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>
View XML file,View XSL file,View results.
Example 2
Display the title of each CD. If it is not the last or second-to-last CD, insert ", " between each CD-title. If it is the last CD, add "!" after the title. If it is the second-to-last CD, add ", and " after it:
<?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>