XSLT:一次循环选择两个元素 [英] XSLT: Loop selecting two elements at a time

查看:38
本文介绍了XSLT:一次循环选择两个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆 xml 文档,作者选择在其中表示一组像这样的笛卡尔点:

I have a bunch of xml documents where the author chose to represent a set of cartesian points like this:

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

This would be equal to the points (0,0) and (1,1).

我想把它改写成

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

但是,我不知道如何在 XSLT 中创建它,除了对每种可能的情况进行硬编码 - 例如对于 4 点集:

However, I cannot figure out how to create this in XSLT, other than hardcoding for each possible case - for instance for a 4-point set:

<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 元素.

There must be a better way to do this? To summarize, I want to create elements like <point x="..." y="..."/>, where x and y are the even/odd-indexed col elements.

推荐答案

当然有通用的方法:

<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:一次循环选择两个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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