xml - 同时迭代两个 for-each 循环

我有一个 XSLT 问题,我想我需要迭代两个 for-each 循环,也许有更好的解决方案。我希望下面的例子能解释我的问题。

我有以下 XML 格式:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <variables>var1 var2 var3 var4 var5</variables>
   <measurement no="1">
      <values>1 2 3 4 5</values>
   </measurement>
   <measurement no="2">
      <values>11 22 33 44 55</values>
   </measurement>
</root>

预期输出:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <record>
      <var1>1</var1>
      <var2>2</var2>
      <var3>3</var3>
      <var4>4</var4>
      <var5>5</var5>
   </record>
   <record>
      <var1>11</var1>
      <var2>22</var2>
      <var3>33</var3>
      <var4>44</var4>
      <var5>55</var5>
   </record>
</root>

来自 Does xslt have split() function? 的解决方案部分为我工作,我设法编写了以下 XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
   <xsl:template match="@*|node()">
      <xsl:copy>
         <xsl:apply-templates select="@*|node()" />
      </xsl:copy>
   </xsl:template>
   <xsl:template match="root/variables" name="tokenize">
      <xsl:param name="separator" select="' '" />
      <xsl:for-each select="tokenize(.,$separator)">
         <xsl:variable name="variable" select="normalize-space(.)" />
         <xsl:element name="{$variable}">xxx</xsl:element>
      </xsl:for-each>
   </xsl:template>
</xsl:stylesheet>

结果是:

<root>
   <var1>xxx</var1>
   <var2>xxx</var2>
   <var3>xxx</var3>
   <var4>xxx</var4>
   <var5>xxx</var5>
   <measurement no="1">
      <values>1 2 3 4 5</values>
   </measurement>
   <measurement no="2">
      <values>11 22 33 44 55</values>
   </measurement>
</root>

但是,我看不出有任何方法可以同时对 进行操作。我需要将变量 的各个元素连接在一起,在每个测量 的单独记录标签中。我会很乐意提供任何帮助!

最佳答案

鲜为人知的 for-each-pair() 函数在这里很有用。

<xsl:template match="measurement">
  <record>
    <xsl:sequence select="for-each-pair(
                           tokenize(/root/variables),
                           tokenize(values),
                           my:gen#2)"/>
  </record>
</xsl:template>

<xsl:function name="my:gen" as="element()">
   <xsl:param name="var" as="xs:string"/>
   <xsl:param name="content" as="xs:string"/>
   <xsl:element name="{$var}">{$content}</xsl:element>
</xsl:function>  

(这是带有 expand-text="yes"的 XSLT 3.0)

https://stackoverflow.com/questions/67985357/

相关文章:

flutter - 错误 : A non-null value must be returned s

awk - 使用 awk 和 gsub 用字符串替换 CSV 的列

ruby - 如何在 ruby​​ 中编写一个采用散列样式、方括号参数的方法,例如 mymethod

Flutter - 墨水池 : Why does onHover() require onTap()

javascript - console.log 在我的输入字段中给出 undefined

kubernetes - 如何在 Kubernetes cronjob 中执行脚本 shell

c++ - std::sort 中用 lambda 函数指定的比较函数是否返回 bool 类型?

flutter - 检查 flutter 中的连接并根据连接状态更改状态

numpy - XGBoost:检查失败:有效:输入数据包含 `inf` 或 `nan`

python - Django Channels - Websocket 连接失败