xsl 中 for-each 和模板之间的区别? [英] differences between for-each and templates in xsl?

查看:27
本文介绍了xsl 中 for-each 和模板之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

xsl:for-eachxsl:template 都用于从 xsl 样式表中的 xml 检索节点.但它们之间的根本区别是什么?请指导我.提前致谢.

Both xsl:for-each and xsl:template are used to retrieve nodes from xml in an xsl stylesheet. But what is the fundamental difference between them? Please guide me. Thanks in advance.

推荐答案

我认为这与理解 推与拉 风格的处理,而不仅仅是比较 xsl:for-eachxsl:template match="...".您经常会看到来自其他学科的程序员使用大量 xsl:ifxsl:choose 和 for 循环,而问题本可以用更优雅的 XSLT 方式解决.

I think this has some what to do with understanding push vs. pull style processing than just comparing xsl:for-each or xsl:template match="...". You often see programmers from another discipline using a lot of xsl:if, xsl:choose and for-loops when the problem could have been solved in a more elegant XSLTish way.

但是对于问题: 在我看来,如果您考虑使用 xsl:for-each 而不是使用 xsl:apply-templates 你需要重新思考.在某些情况下,for 循环适用于 XSLT,但只要匹配的模板会做同样的事情,模板就是要走的路.根据我的经验,您通常可以使用 xsl:apply-templates 代替大多数 xsl:for-each.

But to the question: In my opinion, if you consider using xsl:for-each instead of processing the data with xsl:apply-templates you need to rethink. There are cases where a for-loop is suitable in XSLT, but whenever a matching template would do the same, templates are the way to go. In my experience, you can usually do most xsl:for-each with an xsl:apply-templates instead.

我认为在 for 循环上使用匹配模板的一些好处是:

  • 样式表更易于维护和扩展,尤其是在源数据发生变化时.
  • 正如@chiborg 提到的,模板可以重复使用,因为它们没有内置到特定模板中.与 XSLT 2.0 中的 xsl:next-match 一起,您可以以强大的方式将模板链接在一起.
  • 您不必模仿所有 XSLT 处理器中已经内置的行为,也就是说;使用 xsl:apply-templates 并让处理器为您工作.
  • 此外,我发现推送样式表更容易理解和调试.如果您将样式表信息拆分为执行一项或多项操作的小模板并编写特定的匹配模式,则很容易查看哪个模板在做什么并追踪问题的根源.
  • The stylesheets are easier to maintain and extend especially if source data changes.
  • As @chiborg mentions, templates can be reused since they are not built into a specific template. Together with xsl:next-match in XSLT 2.0 you can chain templates together in powerful ways.
  • You don't have to mimic behavior already built in to all XSLT processors, that is; use xsl:apply-templates and let the processor work for you.
  • Also, I find it easier to understand and debug a push style stylesheet. If you divide your stylesheet info small templates which do one or a few things and write specific matching patterns it's easy to see which template is doing what and trace the source of the problem.

这篇关于xsl 中 for-each 和模板之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆