I hear time and time again about how you should avoid the use of XSLT for-each. That it's your inner imperative programming demon that should be banished.
What's so bad about it?
Does this best practice matter depending on the size of XML (i.e 100 vs 10,000 nodes)?
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.
Templates tend to split up the code more nicely. Also, for-each loops suffer from the fact that people often come to them with the idea that they operate identically to the way for loops work in the major programming languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With