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 if statement in regular programming.


2. Syntax

<xsl:if test="XPath_condition">
   <!-- instructions to execute if condition is true -->
</xsl:if>
  • test attribute: 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 &gt; 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 &gt; 20" checks if the <price> element is greater than 20.

  • Only <book> elements satisfying this condition are included in the output.


5. Key Points

  1. <xsl:if> evaluates a single condition.

  2. If the condition is false, the content inside <xsl:if> is skipped.

  3. For multiple conditions, you can either:

    • Use nested <xsl:if> elements

    • Or use <xsl:choose> (similar to if…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)