【问题标题】:XSLT: Do a group by twice, first within the same tag, and then by 2 different tagsXSLT:按两次分组,首先在同一个标​​签内,然后按 2 个不同的标签
【发布时间】:2018-08-31 19:38:15
【问题描述】:

我想对以下 XML 进行分组:

<DataSet>
  <FirstNode>
    <UniqueKey>111</UniqueKey> 
    <OtherKey>552</OtherKey>
  </FirstNode>
  <FirstNode> 
    <UniqueKey>123</UniqueKey> 
    <OtherKey>552</OtherKey>
  </FirstNode>
  <FirstNode> 
    <UniqueKey>154</UniqueKey> 
    <OtherKey>553</OtherKey>
  </FirstNode>
  <SecondNode>
    <FirstNodeKey>111</FirstNodeKey>
  </SecondNode>
  <SecondNode>
    <FirstNodeKey>123></FirstNodeKey>
  </SecondNode>
  <SecondNode>
    <FirstNodeKey>154></FirstNodeKey>
  </SecondNode>
</DataSet>

我想用 XSLT 生成以下 xml:

  <DataSet>
      <FirstNode>
        <UniqueKey>111</UniqueKey> 
        <OtherKey>552</OtherKey>
      </FirstNode>
      <FirstNode> 
        <UniqueKey>123</UniqueKey> 
        <OtherKey>552</OtherKey>
      </FirstNode>
      <SecondNode>
        <FirstNodeKey>111</FirstNodeKey>
      </SecondNode>
      <SecondNode>
        <FirstNodeKey>123></FirstNodeKey>
      </SecondNode>
 </DataSet>

<DataSet>
      <FirstNode> 
        <UniqueKey>154</UniqueKey> 
        <OtherKey>553</OtherKey>
      </FirstNode>
      <SecondNode>
        <FirstNodeKey>154></FirstNodeKey>
      </SecondNode>
 </DataSet>

基本上我想先按OtherKey对FirstNodes分组,然后按UniqueKey和FirstNodeKey分组。然后每个都应该包含在&lt;DataSet&gt;&lt;/DataSet&gt;中。我可以通过使用分组来做到这一点吗?

提前感谢您的帮助!

【问题讨论】:

  • 请指定您使用的 XSLT 版本。

标签: xslt xslt-grouping


【解决方案1】:

您似乎只是想通过OtherKey 子元素对FirstNode 元素进行分组,然后基于current-group()/UniqueKey 引用任何SecondNode 元素:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:output method="xml" indent="yes"/>

  <xsl:key name="second" match="SecondNode" use="FirstNodeKey"/>

  <xsl:template match="DataSet">
     <xsl:variable name="ds" select="."/>
     <xsl:for-each-group select="FirstNode" group-by="OtherKey">
         <xsl:copy select="$ds">
             <xsl:copy-of select="current-group(), key('second', current-group()/UniqueKey, .)"/>
         </xsl:copy>
     </xsl:for-each-group>
  </xsl:template>

</xsl:stylesheet>

即 XSLT 3 与 Saxon 9.8(例如 https://xsltfiddle.liberty-development.net/3NzcBtw)或 Altova 2018 一起使用,对于 XSLT 2,您可以拼出

         <xsl:copy select="$ds">
             <xsl:copy-of select="current-group(), key('second', current-group()/UniqueKey, .)"/>
         </xsl:copy>

作为

<DataSet> 
     <xsl:copy-of select="current-group(), key('second', current-group()/UniqueKey, $ds)"/>
</DataSet>

当然,如果还有其他节点需要处理,请将 xsl:mode 声明替换为标识模板。

【讨论】:

  • 谢谢!我正在使用 XSLT 2,我会为 使用什么?
猜你喜欢
  • 1970-01-01
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 2014-07-22
相关资源
最近更新 更多