I guess many have been turned off of XSLT just because of this one simple thing - trivial looping is
very hard. By trivial looping I mean something like this (Ruby):
# simple
(1..200).each { |i| puts "<something index=\"#{i}\"/>" }
# more verbose
for i in 1..200
puts "<something index=\"#{i}\"/>"
end
# output is <something index=“1“/> ... <something index=“200“/>
Of course, you'd never generate XML this way :) but it shows a simple way to loop from 1 to 200. How hard is this in XSLT 1? Let's see (XSLT 1.0):
<xsl:template
match="/"> <xsl:call-template name="iterate">
<xsl:with-param name="i" select="1"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="iterate">
<xsl:param name="i"/>
<xsl:if test="$i <= 200">
<something>
<xsl:attribute name="index">
<xsl:value-of select="$i"/>
</xsl:attribute>
</something>
<xsl:call-template name="iterate">
<xsl:with-param name="i" select="$i + 1"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
Whoa, that's a lot of lines! We're simulating iteration by recursion* which is not only inefficient but confusing for beginners. Also, quite a few lines of code to chew. All that for a simple loop?!?
Here's the same loop with the new XSLT, currently W3C candidate recommendation (XSLT 2.0):
<xsl:for-each
select="1 to 300"> <something>
<xsl:attribute name="index" select="." />
</something>
</xsl:for-each>
That's more like it - clean and simple. Apart from sequences (1 to 300) you can also see one other small improvement here - I was able to use select attribute on an xsl:attribute.
XSLT 2.0 is not only better for experienced coders, but for beginners too. Even though many will be lured by even greater simplicity (and likeness to "regular" languages) of XQuery, the language for XML processing will still be XSLT.
*Because of recursion there is a XSLT processor imposed limit on the iteration depth which seems to be about 3400 entries for Altova's XML processor - after that the call stack overflow. Saxon seems to be better in this regard but should have a limit too unless internally this pattern is recognized and manually optimized to avoid recursion, which I doubt.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5