XSLT <xsl:if>Element


The <xsl:if> element is used to perform conditional checks on XML data. It outputs the corresponding content only when the specified condition is true.


<xsl:if> Element

In XSLT, if you need to decide whether to output a piece of content based on the value or state of an XML node, you can use the <xsl:if> element for conditional control.

Syntax

<xsl:if test="expression">
... content to be executed when the condition is true ...
</xsl:if>

Explanation:The test attribute is used to specify the condition expression (an XPath expression). When the expression evaluates to true, the inner content is processed and output.



Where to Place the <xsl:if> Element

Typically, <xsl:if> is used together with loop statements, for example, to filter each node inside <xsl:for-each>:

Example

<?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>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> <th>Price</th> </tr> <xsl:for-each select="catalog/cd"> <xsl:if test="price &gt; 10"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> <td><xsl:value-of select="price"/></td> </tr> </xsl:if> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

Try it Yourself »

Note:The test attribute is required. Its value is an XPath expression, such as comparison operations (> , <, =) or logical judgments.

Explanation:In the above example, only when price is greater than 10 will the corresponding CD be output to the table.

Other Extensions