1. b.93z.org
  2. Notes

xsl:for-each or xsl:apply-templates?

Which operator is preferable—xsl:for-each or xsl:apply-templates—and why?

xsl:for-each works only in case you exactly know the structure of XML document you’re applying transformation to. But xsl:apply-templates is more flexible: it works by defining rules for element handling, that is, when element is encountered, a template you defined is applied. That makes XSL template more friendly to changes in XML document structure. Also it allows you to make a reusable library of rules so you can use in many different cases you haven’t (yet) thought about.

Let’s take a look at an example (key lookup).

You can do it with xsl:for-each:

<xsl:for-each select="document('doc.xml')">
    <xsl:value-of select="key('key', $value)"/>
</xsl:for-each>

You can do it with xsl:apply-templates this way:

<xsl:apply-templates select="document('doc.xml')" mode="lookup">
    <xsl:with-param name="value" select="$value"/>
</xsl:apply-templates>

Or like this:

<xsl:template match="/" mode="lookup">
    <xsl:param name="value"/>
    <xsl:value-of select="key('key', $value)"/>
</xsl:template>

Here real advantage of xsl:for-each is that it is shorter. But don’t use it when value you’re looking for repeats in a document. If you’re new to XSLT, just stick to xsl:apply-templates, so you’ll first fully understand how transformations work, and maybe then use xsl:for-each in cases you know for sure you need it.

© 2008–2017 93z.org