XSLT, XML: Grouping by attribute value

2019-03-02 12:01发布

Which is the best way to group Elements based on attribute value using XSLT? Would it be better to use XSLT 2.0 or higher?

Many thank in advance for your help

Thomas


Original XML:

<transaction>    
  <record type="1" >
    <field number="1" >
        <item >223</item>
    </field>
  </record>

  <record type="14" >
    <field number="1" >
        <item >777</item>
    </field>
  </record>

  <record type="14" >
    <field number="1" >
        <item >555</item>
    </field>
  </record>      
</transaction>

Result after grouping:

<transaction>
  <records type="1" >
      <record type="1" >
        <field number="1" >
            <item >223</item>
        </field>
      </record>
  </records>

  <records type="14" >
      <record type="14" >
        <field number="1" >
            <item >777</item>
        </field>
      </record>

      <record type="14" >
        <field number="1" >
            <item >555</item>
        </field>
      </record>
  </records>
</transaction>

标签: xml xslt
1条回答
\"骚年 ilove
2楼-- · 2019-03-02 12:57

In XSLT 2.0, you can use xsl:for-each-group, but if you are going to do <xsl:for-each-group select="record" group-by="@type"> then you must be positioned on the transaction record at that point.

Additionally, you will need to make use of current-group to get all the record elements within the group.

Try this XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

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

<xsl:template match="transaction"> 
    <xsl:copy>
        <xsl:for-each-group select="record" group-by="@type"> 
            <records type="{current-grouping-key()}" >
                <xsl:apply-templates select="current-group()" />
            </records>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template> 

<xsl:template match="@*|node()"> 
    <xsl:copy> 
        <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 
</xsl:stylesheet> 
查看更多
登录 后发表回答