When to use for-each and when to use apply-templates in xslt?

前端 未结 1 1158
情书的邮戳
情书的邮戳 2021-01-12 14:05

I\'ve heard that most of the time it\'s usually possible (and better) to use apply-templates rather than for-each when writing an XSLT. Is this true? If so, what are the b

相关标签:
1条回答
  • 2021-01-12 14:26

    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> in XSLT 1.0 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.

    On the other side, using <xsl:template> and <xsl:apply-templates> is much more powerful and elegant.

    Here are some of the most important differences between the two approaches:

    1. xsl:apply-templates is much richer and deeper than xsl:for-each, even simply because we don't know what code will be applied on the nodes of the selection -- in the general case this code will be different for different nodes of the node-list.

    2. The code that will be applied can be written way after the xsl:apply templates was written and by people that do not know the original author.

    The FXSL library's implementation of higher-order functions (HOF) in XSLT wouldn't be possible if XSLT didn't have the <xsl:apply-templates> instruction.

    Summary: Templates and the <xsl:apply-templates> instruction is how XSLT implements and deals with polymorphism.

    Reference: See this whole thread: http://www.stylusstudio.com/xsllist/200411/post60540.html

    0 讨论(0)
提交回复
热议问题