Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's so bad about xsl:for-each?

Tags:

xslt

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)?

like image 773
eddiegroves Avatar asked Apr 10 '09 10:04

eddiegroves


2 Answers

Essential difference between <xsl:apply-templates> and <xsl:-for-each> that nobody has pointed out:

  1. <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.

like image 76
Dimitre Novatchev Avatar answered Sep 29 '22 08:09

Dimitre Novatchev


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.

like image 35
dommer Avatar answered Sep 29 '22 08:09

dommer