Re: [xsl] RE:"*NEVER* use for-each"

Subject: Re: [xsl] RE:"*NEVER* use for-each"
From: "Steve Muench" <Steve.Muench@xxxxxxxxxx>
Date: Tue, 27 Feb 2001 10:12:17 -0800
| Yeah..why not? I am using it to iterate for drop-down boxes built
| dynamically, as well as listing any items in a given object for display. I
| am not sure how to do it any other way. I see your example showing to use a
| template..but is that really better? Is it less intensive? Is it faster?
| When should we/should we not use for-each?

Telling people to avoid <xsl:for-each> is bogus advice.
I've run into just as many users confused by default
template rules and the unexpected (for them at least)
processing of whitespace that the <xsl:apply-templates>
model implies, so it's hard to say which is a better
approach for beginniners.

It probably depends on whether a beginner is doing
a project with XSLT that's more like formatting
a Docbook instance-document or more like formatting
a XMLization of database query results. When users are
working with predictably-structured XML (such as XML 
produced from database queries), many tasks can be 
performed just fine with <xsl:for-each>.

It's not a panacea. You cannot get the most out of
XSLT without understanding when to use <xsl:for-each>
and when to use <xsl:apply-templates>, but to scare 
users away from using <xsl:for-each> is not the right
thing to do.

Processing an <xsl:for-each> avoids the step of 
selecting the most relevant template which must
be a non-zero amount of processing time, even in
a highly optimized implementation, so I cannot see
when <xsl:apply-templates> would be faster than
<xsl:for-each>. However, when you need the flexibility
that <xsl:apply-templates> provides, nothing can beat it
for sure.

In my book, I try to conceptually compare a
"single-template, pull-style" stylesheet to
a Java class with all of its code in a single
"main()" method. I try to motivate how writing Java
code which is all written in one big main() method is not
the best approach when you want others to be
able to easily override parts of the processing.
This is because the "method" is the Java class'
unit of overrideability.

I compare a multiple-templates stylesheet to
a Java class that has been nicely factored into
methods that perform the different "subtasks"
that the class needs to perform, so individual
"methods" can be overridden by someone reusing
your work. This conceptually applies to templates
as well in XSLT. They are the unit of overrideability
of a stylesheet.

Steve Muench, Lead XML Evangelist & Consulting Product Manager
BC4J & XSQL Servlet Development Teams, Oracle Rep to XSL WG
Author "Building Oracle XML Applications", O'Reilly

 XSL-List info and archive:

Current Thread