select with if them else statement : if « XSLT stylesheet « XML Tutorial






File: Data.xml

<?xml version="1.0"?>
<cars>
  <make geography="Europe">Alfa Romeo</make>
  <make geography="Europe">Bentley</make>
  <make geography="North America">Chevrolet</make>
  <make geography="North America">Dodge</make>
  <make geography="North America">GMC</make>
  <make geography="Asia">Honda</make>
  <make geography="Asia">Isuzu</make>
  <make geography="?">Quantum</make>
</cars>

File: Transform.xslt

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

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:for-each select="cars/make">
      <xsl:text>&#xA;  Car: </xsl:text>
      <xsl:value-of select="."/>
      <xsl:text> - </xsl:text>
      <xsl:value-of 
        select="if (@geography = 'North America') then 
                  'Domestic car'
                else if (@geography = 'Europe') then 
                  'Import from Europe'
                else if (@geography = 'Asia') then 
                  &quot;It's from Asia&quot;
                (: If it's anything else :)
                else 
                   'We don''t know!'"/>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

Output:


  Car: Alfa Romeo - Import from Europe
  Car: Bentley - Import from Europe
  Car: Chevrolet - Domestic car
  Car: Dodge - Domestic car
  Car: GMC - Domestic car
  Car: Honda - It's from Asia
  Car: Isuzu - It's from Asia
  Car: Quantum - We don't know!








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