XSLT <xsl:if> Element


XSLT Element Reference 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


Examples

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

Example 1

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

Try it yourself »

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:

Example 2

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

Try it yourself »


XSLT Element Reference XSLT Element Reference

Color Picker

colorpicker