RE: [xsl] Apply template?

Subject: RE: [xsl] Apply template?
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Wed, 16 May 2007 17:05:09 +0100
Using for-each isn't wrong. What's wrong is using it because you haven't
worked out how to use apply-templates. You need to be equally comfortable
working with either tool. apply-templates is more powerful because it's
polymorphic. It's more flexible because it separates concerns: what nodes to
process, versus how to process them. It allows the processing of each kind
of node to be overridden (customised) in an importing stylesheet. So
apply-templates is better at handling structures that might vary from one
instance to another or change over time or where some applications might
want to override the behaviour of parts of the transformation. But you don't
always need that power and flexibility.

For example, for-each isn't wrong in the situation where you're processing
an ITEMS element which is always going to contain a sequence of ITEM

You won't normally get a performance benefit by changing a for-each to an
apply-templates (there might in fact be a small cost, though it's unlikely
to be measurable).

A good indicator that a for-each ought to be changed to an apply-templates
is when the body of the for-each consists of an xsl:choose, especially one
that uses tests such as <xsl:when test="name()='bilbo'">.

Michael Kay

> -----Original Message-----
> From: Danny Leblanc [mailto:leblancd@xxxxxxxxxxxxxxxxxxx] 
> Sent: 16 May 2007 16:02
> To: xsl-list@xxxxxxxxxxxxxxxxxxxxxx
> Subject: [xsl] Apply template? 
> Good day everyone,
>   I have read in the past here that most people who are not 
> "used" to XSLT tend to use for-each when an apply template 
> would be the better route. I have received the following XSLT file.
> <?xml version="1.0" encoding="UTF-8"?>
> <xsl:stylesheet version="2.0" 
> xmlns:xsl="";>
>   <xsl:output method="xml" version="1.0" encoding="UTF-8" 
> indent="yes"/>
>   <xsl:template match="/">
>     <A>
>       <B>
>          <xsl:for-each select="/A/B/C">
>           <xsl:sort order = "ascending" data-type = "number" 
> select = "D"/>
>           <xsl:copy>
>             <xsl:apply-templates select="@*|node()"/>
>           </xsl:copy>
>         </xsl:for-each>
>       </B>
>     </A>
>   </xsl:template>
>   <xsl:template match="@*|node()">
>     <xsl:copy>
>       <xsl:apply-templates select="@*|node()"/>
>     </xsl:copy>
>   </xsl:template>
> </xsl:stylesheet>
>   In a case like this, would there be a better way to handle 
> this using apply templates? Would there be a performance gain 
> by using apply templates instead? I tried to put one together 
> but to date have not had much success but just wanted to 
> ensure that switching to apply templates would be the correct 
> way to go.
>   Thank you for all advice given.
> Danny

Current Thread