Re: [xsl] Is xsl:for-each "syntactic sugar"?

Subject: Re: [xsl] Is xsl:for-each "syntactic sugar"?
From: Mukul Gandhi <gandhi.mukul@xxxxxxxxx>
Date: Fri, 7 May 2010 18:57:33 +0530
Following are definitions of "for-each" and "apply-templates", from
XSLT 2.0 spec:

http://www.w3.org/TR/xslt20/#element-for-each
"The xsl:for-each instruction processes each item in a sequence of
items, evaluating the sequence constructor within the xsl:for-each
instruction once for each item in that sequence."

http://www.w3.org/TR/xslt20/#element-apply-templates
"The xsl:apply-templates instruction takes as input a sequence of
nodes (typically nodes in a source tree), and produces as output a
sequence of items; these will often be nodes to be added to a result
tree."

Therefore, xsl:apply-templates can work only on a sequence of nodes,
whereas xsl:for-each can process a sequence of items (i.e, nodes plus
atomic values). IMHO, this is a key difference between these
constructs.

The processing model of xsl:for-each and apply-templates is also quite
distinct. An apply-templates while in process, searches for a template
rule, that matches the pattern of node (which means, that nodes in the
input sequence of apply-templates can have different template
targets).

Whereas, with for-each it's implied that, for every item in the input
sequence, the sequence constructor to be applied on an item is same.
This is another key difference between these two constructs.

Stylesheet authors, could make design decisions appropriately (whether
to use, for-each or apply-templates), to solve use-cases available
with them.

On Fri, May 7, 2010 at 6:16 PM, David Carlisle <davidc@xxxxxxxxx> wrote:
> On 07/05/2010 13:28, Mukul Gandhi wrote:
>>
>> B As you said, many XSLT programming situations could be
>> equivanetly handled by for-each& B apply-templates.
>
> Not "many", all uses of for-each can be equivalently handled by
> apply-templates.
>
>
>
> ..
> <xsl:variable name="a">...</xsl:variable>
> ..
> <xsl:variable name="z">...</xsl:variable>
> ...
> <xsl:for-each select="foo">
> B body
> </xsl:for-each>
>
> is
>
>
>
> .
> <xsl:variable name="a">...</xsl:variable>
> ..
> <xsl:variable name="z">...</xsl:variable>
> ...
> <xsl:apply-templates select="foo" mode="unique-d">
> B <xsl:with-param name="a" select="$a"/>
> B <xsl:with-param name="z" select="$z"/>
> </xsl:apply-templates>
>
>
> ...
>
> <xsl:template match="/|node()" mode="unique-id">
> B <xsl:param name="a"/>
> B <xsl:param name="z"/>
> B body
> </xsl:template>
>
> so xsl:for-each is just really a minor syntactic variation on
> apply-templates for a mode with only one template, in that you can inline
> the template body into the call. If the body uses variable references then
> you need to use parameters in the apply-template version to keep them in
> scope, but it's a purely syntactic transformation.
>
>
>
> David



--
Regards,
Mukul Gandhi

Current Thread