tags:

views:

242

answers:

4

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

+4  A: 

It's generally a matter of code style. If you're doing a for-each which is rather short, and needs to access variables from the parent block, it may be clearer to do a for-each there, rather than applying templates and passing in as parameters anything more that it needs.

There are definitely times that using templates is clearer, and definitely times that using for-each is clearer. They're both useful tools.

Peter Cooper Jr.
+2  A: 

I also think that it's a matter of style.

I have seen projects where XSLT stylesheets hardly used any <xsl:apply-templates> at all. They always used <xsl:call-template> instead. This is not so much a functional, but rather a procedural coding. And this approach inevitably leads you to exessive use of <xsl:for-each>.

Personally, I'll always prefer the style you suggested in your question. But it's a question of team management, skill and consistency that'll let you prefer one style or another.

mkoeller
+3  A: 

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.

Dimitre Novatchev
+1  A: 

I use for-each quite often because I have to build variables which are sub-sets of larger xml files.

<xsl:variable name="foo">
  <xsl:for-each select="document('bar.xml')/item">
    <xsl:if test="baz = bax">
      <xsl:copy-of select="."/>
    </xsl:if>
  </xsl:for-each>
</xsl:variable>

Is that possible with a template?

It may be that I'm one of those programmers who can't see the native XSL way to do things...

AmbroseChapel