使用 XSLT 对 XML 节点进行并行迭代 [英] Parallel iteration over XML nodes with XSLT
问题描述
我有一个这样的 XML:
I have an XML of this kind:
<xml>
<node1>1.1</node1>
<node1>1.2</node1>
<node1>1.3</node1>
<node2>2.1</node2>
<node2>2.2</node2>
<node2>2.3</node2>
<node3>3.1</node3>
<node3>3.2</node3>
<node3>3.3</node3>
</xml>
我想得到以下输出:
线:1.1 + 2.1 + 3.1
行:1.2 + 2.2 + 3.2
线:1.3 + 2.3 + 3.3
and I want to get the following output:
line: 1.1 + 2.1 + 3.1
line: 1.2 + 2.2 + 3.2
line: 1.3 + 2.3 + 3.3
有没有一种方法可以同时迭代这些节点并跟踪我在三个列表中的每一个中的当前位置,或者我是否必须将这些项目包装成一个更大的块并迭代块?
Is there a way I can iterate over these nodes simultaneously and keep track of my current position in each of three lists or do I have to wrap these items into a bigger block and iterate over blocks?
我使用的是 XSL 1.0.
I'm using XSL 1.0.
推荐答案
就这么简单:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node1">
<xsl:variable name="vPos" select="position()"/>
<xsl:value-of select=". + ../node2[$vPos] + ../node3[$vPos]"/>
<xsl:text>
</xsl:text>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
当此转换应用于以下 XML 文档时(基于提供的文档):
<xml>
<node1>1</node1>
<node1>2</node1>
<node1>3</node1>
<node2>4</node2>
<node2>5</node2>
<node2>6</node2>
<node3>7</node3>
<node3>8</node3>
<node3>9</node3>
</xml>
产生想要的、正确的结果:
12
15
18
请注意:
在 XSLT 1.0 和 XSLT 2.0 中,可以使用 FXSL 模板/function
zip-with3()
.
在 XPath 3.0 (XSLT 3.0) 中将有一个标准函数 map-pairs()
,但是没有map-tripples()
标准函数.可以使用此函数生成中间结果,然后再次使用它生成最终结果.
In XPath 3.0 (XSLT 3.0) there will be a standard function map-pairs()
, but there is no map-tripples()
standard function. One can use this function to produce an intermediate result and then use it again to produce the final result.
正如 Ian Roberts 所指出的,这个解决方案中 xsl:strip-space
的存在很重要——如果没有它,position()
函数会产生不同的结果,并且转换未按要求执行.
As noted by Ian Roberts, the presence of xsl:strip-space
in this solution is important -- without it the position()
function produces different results and the transformation doesn't perform as required.
这篇关于使用 XSLT 对 XML 节点进行并行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!