在 xslt 中何时使用 for-each 以及何时使用 apply-templates?
我听说大多数时候在编写 XSLT 时通常可以(而且更好)使用 apply-templates 而不是 for-each。这是真的吗?如果是这样,使用 apply-template 有什么好处?
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 benefits of using apply-templates?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果确切地知道
是如何处理的,那么使用
绝不会有害。问题在于,许多具有命令式编程经验的 XSLT 新手将
视为他们最喜欢的 PL 中的“循环”的替代品,并认为这允许他们执行不可能的事情——例如增加计数器或对已定义的
进行任何其他修改。XSLT 1.0 中
的一个不可或缺的用途是更改当前文档 —— 为了能够使用key()
,通常需要这样做。 code> 文档上的函数,与当前源 XML 文档不同,例如,有效访问驻留在其自己的 xml 文档中的查找表。另一方面,使用
和
更加强大和优雅。以下是这两种方法之间的一些最重要的区别:
xsl:apply-templates
比xsl:for 更丰富、更深入-每个
,甚至只是因为我们不知道什么代码将应用于
选择——在一般情况下,此代码将有所不同
节点列表的不同节点。
将应用的代码
可以在编写
xsl:apply template
s之后编写并通过不知道原作者的人。
FXSL 库不可能在 XSLT 中实现高阶函数 (HOF)< /strong> 如果 XSLT 没有
指令。摘要:模板和
指令是 XSLT 实现和处理多态性的方式。参考:查看整个帖子:http:// www.stylusstudio.com/xsllist/200411/post60540.html
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 thekey()
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:
xsl:apply-templates
is much richer and deeper thanxsl:for-each
, evensimply 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.
The code that will be applied
can be written way after the
xsl:apply template
s was written and bypeople 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