XSLT:循环一次选择两个元件(XSLT: Loop selecting two elements

2019-06-26 00:26发布

我有一大堆的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>

这等于点(0,0)和(1,1)。

我想改写这个作为

<set>
  <point x="0" y="0"/>
  <point x="1" y="1"/>
</set>

然而,我无法弄清楚如何在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>
  ...

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

Answer 1:

当然有一个通用的方法:

<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>

我的输出:

<set>
  <point x="0" y="0" />
  <point x="1" y="1" />
</set>


文章来源: XSLT: Loop selecting two elements at a time
标签: xslt