Partager via


xsl:if Element

A version of this page is also available for

Windows Embedded CE 6.0 R3

4/8/2010

Allows simple conditional template fragments.

Syntax

<xsl:if
  test = boolean expression>
</xsl:if>

Attributes

  • test
    Required. The condition in the source data to test. If the expression in this attribute evaluates to true when cast to a Boolean, the contents of <xsl:if> are placed in the output. Node-sets are cast to a Boolean True if they contain at least one node.

Element Information

Number of occurrences

Unlimited

Parent elements

xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:for-each, xsl:otherwise, xsl:param, xsl:processing-instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements

Child elements

xsl:apply-templates, xsl:attribute, xsl:call-template, xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:for-each, xsl:processing-instruction, xsl:text, xsl:value-of, xsl:variable, output elements

Remarks

The content is a template. The expression is evaluated, and the resulting object is converted to a Boolean. If the result is True, the content template is instantiated; otherwise, nothing is created.

Examples

In the following example, the names in a group of names are formatted as a comma-separated list.

<xsl:template match="namelist/name">
  <xsl:apply-templates/>
  <xsl:if test="position()!=last()">, </xsl:if>
</xsl:template>

Another way to accomplish this is by reversing the logic to do a check if this name is the first. In some circumstances this performs better than the above example since last() requires that the entire set of names be found and counted, while this one does not.

<xsl:template match="namelist/name">
  <xsl:if test="position()!=1">, </xsl:if>
  <xsl:apply-templates/>
</xsl:template>

The following colors every other table row yellow.

<xsl:template match="item">
  <tr>
    <xsl:if test="position() mod 2 = 0">
       <xsl:attribute name="bgcolor">yellow</xsl:attribute>
    </xsl:if>
    <xsl:apply-templates/>
  </tr>
</xsl:template>

This example inserts the text "International Stock" when the "stock" element has an "international" attribute.

<xsl:template match="stock">
  <xsl:if test="@international">International Stock</xsl:if>
  <xsl:apply-templates />
</xsl:template>

See Also

Reference

XSLT Elements

Concepts

Conditional Templates