Could anybody give an example when xsl:foreach is really useful?
I just made a project and concluded that everywhere I could replace it with appropriate <xsl:apply-templates />. <xsl:if> and <xsl:when/> sometimes make code shorter and i cannot effectively replace it with <apply-templates/> in functional style.
Is <xsl:foreach> considered harmful anyway?
Well, thanks everybody, i really couldn’t choose the answer among the best. i think it would be better to collect different cases.
Sorry for somebody downvoting answers – it’s not me:)
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.