xsl:if

  1. if_1-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product id="p1" stock="4"/>
  5. </products>
  1. if_1-stylesheet.xsl

  2. <?xml version="1.0"?>
  3. <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  4.   <xsl:variable name="x" select="products/product"/>
  5.   <xsl:output indent="yes"/>
  6.   <xsl:template match="/">
  7.     <products>
  8.       <product>
  9.         <xsl:attribute name="id" select="$x/@id"/>
  10.         <xsl:attribute name="stock" select="$x/@stock"/>
  11.         <xsl:if test="$x/@stock &lt; 5">
  12.           <xsl:attribute name="reorder" select="'yes'"/>
  13.         </xsl:if>
  14.         </product>
  15.     </products>
  16.   </xsl:template>
  17. </xsl:stylesheet>
  1. if_1-output.xml

  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <products>
  4.   <product id="p1" stock="4" reorder="yes"/>
  5. </products>

Comment

The xsl:if element can be nested inside another xsl:if element. If two xsl:if elements follow one another it is probably time to use a real "switch" instead that is xsl:choose. In XPath 2.0 expressions can use if-then-else like this: <xsl:value-of select="if (…) then 'a' else 'b'"/>

Updated 2009-03-19