xsl:apply-templates (1)

  1. apply-templates_1-input.xml

  2. <?xml version="1.0"?>
  3. <products><product id="p1" price="3250" stock="4"/>
  4.   <product id="p2" price="1000" stock="5"/>
  5.   <product id="p3" price="1200" stock="19"/>
  6.   <product id="p4" price="1500" stock="5"/>
  7.   <product id="p5" price="1225" stock="3"/>
  8. </products>
  1. apply-templates_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:apply-templates/>
  8.     </PRODUCTS>
  9.   </xsl:template>
  10.   <xsl:template match="product">
  11.     <PRODUCT id="{@id}" price="{@price}" stock="{@stock}"/>
  12.   </xsl:template>
  13.   <xsl:template match="product[@id = 'p2']"/>
  14.   <xsl:template match="product[@stock &lt;= 3]">
  15.     <PRODUCT id="{@id}" price="{@price}" stock="{@stock}" reorder="yes"/>
  16.   </xsl:template>
  17. </xsl:stylesheet>
  1. apply-templates_1-output.xml

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

Comment

In the stylesheet above there are no benefits compared to a stylesheet with just one template and an xsl:choose switch inside an xsl:for-each. But many templates give us the option of reusing templates. They can be placed in other stylesheets we can include using xsl:include or import using xsl:import into the main stylesheet.

Note that an XSLT processor has some build in default templates. If an element is found that is not matched by a template in the stylesheet, the XSLT processor should say "xsl:apply-templates" in order to continue. See: http://www.w3.org/TR/xslt20/#built-in-rule.

Updated 2009-03-19