xsl:choose

  1. choose_1-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product id="p1" stock="4"/>
  5. </products>
  1. choose_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:choose>
  11.           <xsl:when test="not($x/@stock)">
  12.             <xsl:message terminate="yes">Stock attribute is missing.</xsl:message>
  13.           </xsl:when>
  14.           <xsl:when test="not(number($x/@stock))">
  15.             <xsl:message terminate="yes">Value of stock must be a number.</xsl:message>
  16.           </xsl:when>
  17.           <xsl:when test="$x/@stock &lt; 0">
  18.             <xsl:message terminate="yes">Value of stock must be >= 0.</xsl:message>
  19.           </xsl:when>
  20.           <xsl:otherwise>
  21.             <xsl:attribute name="stock" select="$x/@stock"/>
  22.           </xsl:otherwise>
  23.         </xsl:choose>
  24.       </Product>
  25.     </Products>
  26.   </xsl:template>
  27. </xsl:stylesheet>
  1. choose_1-output.xml

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

Comment

At least one xsl:when must be child of xsl:choose. The order of xsl:when and the tests must be done carefully: as soon as a test is negative the switch has found its way.

Updated 2009-03-19