From http://www.w3schools.com (Copyright Refsnes Data)

XSLT <xsl:if> Element


XSLT Element Reference Complete XSLT Element Reference

Definition and Usage

The <xsl:if> element contains a template that will be applied only if a specified condition is true.

Tip: Use <xsl:choose> in conjunction with <xsl:when> and <xsl:otherwise> to express multiple conditional tests!


Syntax

<xsl:if
test="expression">
<!-- Content: template -->
</xsl:if>

Attributes

Attribute Value Description
test expression Required. Specifies the condition to be tested

Example 1

Select the values of title and artist IF the price of the CD is higher than 10:

<?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 &gt; 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 the XML file, View the XSL file, and View the result

Example 2

Display the title of each CD. Insert ", " between each CD-title if it is not the last CD or the last but one. If it is the last CD, add "!" behind the title. If it is the last but one CD, add ", and " behind the title:

<?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>


XSLT Element Reference Complete XSLT Element Reference

From http://www.w3schools.com (Copyright Refsnes Data)