Essential difference between <xsl:apply-templates>
and <xsl:-for-each>
that nobody has pointed out:
<xsl:apply-templates>
is really something much more than a nicer, more elegant equivalent of <xsl:for-each>
:
xsl:apply-templates
is much richer and deeper than xsl:for-each
, even
simply because we don't know what code will be applied on the nodes of
the selection -- in the general case this code will be different for
different nodes of the node-list.
Also, the code that will be applied
can be written way after the xsl:apply templates was written and by
people that do not know the original author.
_2. On the other side, using <xsl:for-each>
is in no way harmful if one knows exactly how an <xsl:for-each>
is processed.
The trouble is that a lot of newcomers to XSLT that have experience in imperative programming take <xsl:for-each>
as a substitute of a "loop" in their favorite PL and think that it allows them to perform the impossible -- like incrementing a counter or any other modification of an already defined <xsl:variable>
.
One indispensable use of <xsl:for-each>
is to change the current document -- this is often needed in order to be able to use the key() function on a document, different from the current source XML document, for example to efficiently access lookup-table that resides in its own xml document.