使用 XSLT 根据属性值对元素进行分组的最佳方法是什么?
使用 XSLT 2.0 或更高版本会更好吗?
非常感谢您的帮助
Thomas
原始 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>
分组后结果:
<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
记录当时的情况。
此外,您还需要利用current-group
得到所有的record
组内的元素。
试试这个 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)