XSLT、XML:按属性值分组 [英] XSLT, XML: Grouping by attribute value

查看:35
本文介绍了XSLT、XML:按属性值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 XSLT 根据属性值对元素进行分组的最佳方法是什么?使用 XSLT 2.0 或更高版本会更好吗?

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?

非常感谢您的帮助

托马斯

原始 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>

推荐答案

在 XSLT 2.0 中,您可以使用 xsl:for-each-group,但如果您打算使用 <xsl:for-each-group select="record" group-by="@type"> 那么你必须在那个点定位在 transaction 记录上.

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.

此外,您需要使用 current-group 来获取组内的所有 record 元素.

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

试试这个 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> 

这篇关于XSLT、XML:按属性值分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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