The Element: Conditional Processing : if « XSLT stylesheet « XML Tutorial






The xsl:if element tests whether a Boolean condition is true or false. 
If it is true, then the content of the xsl:if element is instantiated. 
If it is false, then nothing specified inside the xsl:ifelement is added to the result tree. 

File: Data.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<sales>
 <source>
  <title>Book</title>
  <url>http://www.java2s.com</url>
  <amounts estimate="true" year="2002"/>
 </source>
 <nation>
  <name>USA</name>
  <capital>DC</capital>
  <amount>32277942</amount>
  <cc>dz</cc>
 </nation>
 <nation>
  <name>Canada</name>
  <capital>Ottwa</capital>
  <amount>6373002</amount>
  <cc>bi</cc>
 </nation>
 <nation>
  <name>Maxico</name>
  <capital>Maxico City</capital>
  <amount>4465651</amount>
  <cc>er</cc>
 </nation>
</sales>


File: Transform.xslt

<?xml version="1.0" encoding="US-ASCII"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" />

  <xsl:template match="sales">
    <xsl:apply-templates select="nation" />
  </xsl:template>

  <xsl:template match="nation">
    <xsl:text> * </xsl:text>
    <xsl:value-of select="name" />
    <xsl:if test="amount > 10000000">
      <xsl:text> (> 10M)</xsl:text>
    </xsl:if>
    <xsl:text>&#10;</xsl:text>
  </xsl:template>

</xsl:stylesheet>

Output:

 * USA (> 10M)
 * Canada
 * Maxico








5.44.if
5.44.1.The Element: Conditional Processing
5.44.2.Use if statement to test if an element as an attribute
5.44.3.Check two attributes
5.44.4.Nested if statement
5.44.5.if test="not(preceding-sibling::address[zip=$lastZip])"
5.44.6.if test="(position() mod 2) = 1"
5.44.7.select with if them else statement
5.44.8.xsl:if instruction enables conditional processing
5.44.9.Use if statement to check whether it is the last