[英]XSLT, XML: Grouping by attribute value
使用XSLT根據屬性值對元素進行分組的最佳方法是哪種? 使用XSLT 2.0或更高版本會更好嗎?
在此先感謝您的幫助
湯瑪士
原始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
來獲取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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.