xsl:for-each (1)

  1. for-each_1-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product id="p1">
  5.     <price>3250</price>
  6.     <stock>4</stock>
  7.   </product>
  8.   <product id="p2">
  9.     <price>1000</price>
  10.     <stock>5</stock>
  11.   </product>
  12. </products>
  1. for-each_1-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.         <PRODUCT id="{@id}">
  9.           <PRICE>
  10.             <xsl:value-of select="price"/>
  11.           </PRICE>
  12.           <STOCK>
  13.             <xsl:value-of select="stock"/>
  14.           </STOCK>
  15.         </PRODUCT>
  16.       </xsl:for-each>
  17.     </PRODUCTS>
  18.   </xsl:template>
  19. </xsl:stylesheet>
  1. for-each_1-output.xml

  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <PRODUCTS>
  4.   <PRODUCT id="p1">
  5.     <PRICE>3250</PRICE>
  6.     <STOCK>4</STOCK>
  7.   </PRODUCT><PRODUCT id="p2">
  8.     <PRICE>1000</PRICE>
  9.     <STOCK>5</STOCK>
  10.   </PRODUCT>
  11. </PRODUCTS>

Comment

Using only one template and a xsl:for-each is very common in simple transformations.

Updated 2009-03-19