首页 > 解决方案 > XSLT:按两次分组,首先在同一个标​​签内,然后按 2 个不同的标签

问题描述

我想对以下 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分组。然后每个都应该包含在<DataSet></DataSet>. 我可以通过使用分组来做到这一点吗?

在此先感谢您的帮助!

标签: xsltxslt-grouping

解决方案


看来您只是想FirstNode按子元素对元素进行分组OtherKey,然后SecondNode基于以下内容引用任何元素current-group()/UniqueKey

<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声明替换为标识模板。


推荐阅读