Both xsl:for-each
and xsl:template
are used to retrieve nodes from xml in an xsl stylesheet. But what is the fundamental difference between them? P
I think this has some what to do with understanding push vs. pull style processing than just comparing xsl:for-each
or xsl:template match="..."
. You often see programmers from another discipline using a lot of xsl:if
, xsl:choose
and for-loops when the problem could have been solved in a more elegant XSLTish way.
But to the question: In my opinion, if you consider using xsl:for-each
instead of processing the data with xsl:apply-templates
you need to rethink. There are cases where a for-loop is suitable in XSLT, but whenever a matching template would do the same, templates are the way to go. In my experience, you can usually do most xsl:for-each
with an xsl:apply-templates
instead.
Some benefits as I see it of using matching templates over a for-loop are:
xsl:next-match
in XSLT 2.0 you can chain templates together in powerful ways.xsl:apply-templates
and let the processor work for you.