XSLT:循环一次选择两个元素

car*_*ett 7 xslt

我有一堆xml文档,作者选择代表一组笛卡尔点,如下所示:

<row index="0">
  <col index="0">0</col>
  <col index="1">0</col>
  <col index="2">1</col>
  <col index="3">1</col>
</row>
Run Code Online (Sandbox Code Playgroud)

这将等于点(0,0)和(1,1).

我想把它重写为

<set>
  <point x="0" y="0"/>
  <point x="1" y="1"/>
</set>
Run Code Online (Sandbox Code Playgroud)

但是,除了针对每种可能情况的硬编码之外,我无法弄清楚如何在XSLT中创建它 - 例如对于4点集:

<set>
  <point>
    <xsl:attribute name="x"><xsl:value-of select="col[@index = 0]"/></xsl:attribute>
    <xsl:attribute name="y"><xsl:value-of select="col[@index = 1]"/></xsl:attribute>
  </point>
  <point>
    <xsl:attribute name="x"><xsl:value-of select="col[@index = 1]"/></xsl:attribute>
    <xsl:attribute name="y"><xsl:value-of select="col[@index = 2]"/></xsl:attribute>
  </point>
  ...
Run Code Online (Sandbox Code Playgroud)

必须有更好的方法来做到这一点?总而言之,我想创建一些元素<point x="..." y="..."/>,其中x和y是偶数/奇数索引col元素.

Tom*_*lak 9

当然有一种通用的方式:

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>

  <xsl:template match="row">
    <set>
      <xsl:apply-templates select="
        col[position() mod 2 = 1 and following-sibling::col]
      " />
    </set>
  </xsl:template>

  <xsl:template match="col">
    <point x="{text()}" y="{following-sibling::col[1]/text()}" />
  </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

输出给我:

<set>
  <point x="0" y="0" />
  <point x="1" y="1" />
</set>
Run Code Online (Sandbox Code Playgroud)