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

前端 未结 1 1172
情书的邮戳
情书的邮戳 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 is in no way harmful if one knows exactly how an is processed.

    The trouble is that a lot of newcomers to XSLT that have experience in imperative programming take 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 .

    One indispensable use of 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 and 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 instruction.

    Summary: Templates and the instruction is how XSLT implements and deals with polymorphism.

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

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