我知道XSLT在程序性方面不起作用,但遗憾的是我已经使用过程语言的时间太长了.任何人都可以通过简单的术语解释应用模板的工作原理并帮助像我这样的厚实理解来帮助我.
是什么让您认为程序性术语不适用于此?这只是调用约定比传统上预期的更隐式,因为涉及到一个看不见的上下文.一切apply-templates都可以用程序术语表达.
基本上,apply-templates只不过是一个for-each循环.从您当前在文档中的位置(上下文,想想" this")开始,它遍历子节点.
对于每个子节点,处理器选择xsl:template具有最高优先级的匹配(基于它们各自match和priority属性),将上下文设置为手边的子节点并运行该模板(想想" function").模板返回后,上下文会快速返回,这是下一个孩子的回合.
即使事情变得递归(在XSLT中有些难以避免),整个过程也不会变得更复杂.移动上下文"指针",并调用模板.
您可以apply-templates使用以下select属性限制迭代的节点集:
<!-- all children of the context node regardless -->
<xsl:apply-templates />
<!-- all children of the context node being "data" with a @name of "Foo" -->
<xsl:apply-templates select="data[@name='Foo']" />
Run Code Online (Sandbox Code Playgroud)
如果您愿意,可以在迭代之前对节点集进行排序:
<!-- all children of the context node being "data" with a @name of "Foo",
ordered by their respective "detail" count -->
<xsl:apply-templates select="data[@name='Foo']">
<xsl:sort select="count(detail)" data-type="number" order="descending"/>
</xsl:apply-templates>
Run Code Online (Sandbox Code Playgroud)
如果需要,您可以将参数传递给模板,就像使用常规函数调用一样:
<!-- pass in some parameter -->
<xsl:apply-templates select="data[@name='Foo']">
<xsl:with-param name="DateSetIcon" select="$img_src" />
</xsl:apply-templates>
Run Code Online (Sandbox Code Playgroud)
这就是它的全部内容.
编辑:
我知道最后的评论有点挑衅.这是非常有意的,因为基本了解它是如何apply-templates或多或少地起作用的.不是你要定义要调用的模板,而是让处理器为你选择合适的模板这一事实带来的影响和可能性当然比未经训练的耳朵听起来更大.整个事物的陈述/隐含方法肯定需要一些时间才能融入其中.