xsl:for-each (3)

  1. for-each_3-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product id="p1" price="3250" stock="4"/>
  5.   <product id="p2" price="1000" stock="5"/>
  6.   <product id="p3" price="1200" stock="19"/>
  7.   <product id="p4" price="1500" stock="5"/>
  8.   <product id="p5" price="1225" stock="3"/>
  9. </products>
  1. for-each_3-stylesheet.xsl

  2. <?xml version="1.0"?>
  3. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  4.   <xsl:output indent="yes"/>
  5.   <xsl:template match="/">
  6.     <PRODUCTS>
  7.       <xsl:for-each select="products/product">
  8.         <xsl:choose>
  9.           <xsl:when test="@id = 'p2'"/>
  10.           <xsl:when test="@stock &lt;= 3">
  11.             <PRODUCT id="{@id}" price="{@price}" stock="{@stock}" reorder="yes"/>
  12.           </xsl:when>
  13.           <xsl:otherwise>
  14.             <PRODUCT id="{@id}" price="{@price}" stock="{@stock}"/>
  15.           </xsl:otherwise>
  16.         </xsl:choose>
  17.       </xsl:for-each>
  18.     </PRODUCTS>
  19.   </xsl:template>
  20. </xsl:stylesheet>
  1. for-each_3-output.xml

  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <PRODUCTS>
  4.   <PRODUCT id="p1" price="3250" stock="4"/>
  5.   <PRODUCT id="p3" price="1200" stock="19"/>
  6.   <PRODUCT id="p4" price="1500" stock="5"/>
  7.   <PRODUCT id="p5" price="1225" stock="3" reorder="yes"/>
  8. </PRODUCTS>

Comment

The above works and it's ok but when we have a template with an xsl:choose switch inside an xsl:for-each it is high time finding a better structure for the stylesheet using many templates and xsl:apply-templates.

Updated 2009-03-19