XSLT - <xsl:if> in XSLT.
1. What <xsl:if> Is
-
<xsl:if>is a conditional statement in XSLT. -
It allows you to execute a set of instructions only if a condition is true.
-
Think of it like an
ifstatement in regular programming.
2. Syntax
<xsl:if test="XPath_condition">
<!-- instructions to execute if condition is true -->
</xsl:if>
-
testattribute: Contains an XPath expression that evaluates to true or false. -
The content inside
<xsl:if>executes only when the test is true.
3. Example XML
<library>
<book>
<title>1984</title>
<price>15</price>
</book>
<book>
<title>Brave New World</title>
<price>25</price>
</book>
</library>
4. Example XSLT Using <xsl:if>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/library">
<h2>Books Priced Above $20</h2>
<ul>
<xsl:for-each select="book">
<xsl:if test="price > 20">
<li>
<xsl:value-of select="title"/> - $<xsl:value-of select="price"/>
</li>
</xsl:if>
</xsl:for-each>
</ul>
</xsl:template>
</xsl:stylesheet>
Output:
<h2>Books Priced Above $20</h2>
<ul>
<li>Brave New World - $25</li>
</ul>
Explanation:
-
The
test="price > 20"checks if the<price>element is greater than 20. -
Only
<book>elements satisfying this condition are included in the output.
5. Key Points
-
<xsl:if>evaluates a single condition. -
If the condition is false, the content inside
<xsl:if>is skipped. -
For multiple conditions, you can either:
-
Use nested
<xsl:if>elements -
Or use
<xsl:choose>(similar toif…else if…else)
-
6. Quick Comparison
| Feature | <xsl:if> |
<xsl:choose> |
|---|---|---|
| Condition | Single test | Multiple tests (when, otherwise) |
| Use | Simple filtering | Complex branching |
| Skips content if false | Yes | Yes (depending on when/otherwise) |