Name

<xsl:if>

Implements an if statement. It contains a test attribute and an XSLT template. If the test attribute evaluates to the boolean value true, the XSLT template is processed. This element implements an if statement only; if you need an if-then-else statement, use the <xsl:choose> element with a single <xsl:when> and a single <xsl:otherwise>.

Category

Instruction.

Required Attribute

test

Contains a boolean expression. If it evaluates to the boolean value true, then the XSLT template inside the <xsl:if> element is processed.

Optional Attributes

None.

Content

An XSLT template.

Appears in

<xsl:if> appears inside a template.

Defined in

[1.0] XSLT section 9.1, “Conditional Processing with xsl:if.”

[2.0] XSLT section 8.1, “Conditional Processing with xsl:if.”

Example

We’ll illustrate the <xsl:if> element with the following stylesheet:

<?xml version="1.0"?>
<!-- if.xsl -->
<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:text>&#xA;</xsl:text>
    <xsl:text>Here are the odd-numbered items from the list:</xsl:text>
    <xsl:text>&#xA;</xsl:text>
    <xsl:for-each select="list/listitem">
      <xsl:if test="(position() mod 2) = 1">
        <xsl:number format="1. "/>
        <xsl:value-of select="."/>
        <xsl:text>&#xA;</xsl:text>
      </xsl:if>
    </xsl:for-each>
  </xsl:template>
  
</xsl:stylesheet>

This stylesheet uses the <xsl:if> element to see whether a given <listitem>’s position is an odd number. If it is, we write it to the result tree. We’ll test our ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.