這裏是一個更簡單的解決(完全 「推式」,沒有<xsl:for-each>
,沒有嵌套,沒有<xsl:variable>
,沒有current()
,沒有//
,無軸):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:key name="kGoodsByType" match="/*/*" use="a"/>
<xsl:template match=
"/*/*[generate-id()
=
generate-id(key('kGoodsByType', a)[1])
]
">
<group type="{a}">
<xsl:apply-templates select="key('kGoodsByType', a)/b"/>
</group>
</xsl:template>
<xsl:template match="b">
<value v="{.}"/>
</xsl:template>
<xsl:template match="*/* | text()" priority="-1"/>
</xsl:stylesheet>
當這種轉變應用所提供的XML文檔:
<Test>
<grapes>
<a>TypeA</a>
<b>value1</b>
</grapes>
<oranges>
<a>TypeB</a>
<b>value2</b>
</oranges>
<apples>
<a>TypeA</a>
<b>value3</b>
</apples>
</Test>
通緝,協rrect結果產生:
<group type="TypeA">
<value v="value1"/>
<value v="value3"/>
</group>
<group type="TypeB">
<value v="value2"/>
</group>
說明:使用爲重點的a
孩子的字符串值/*/*
Muenchian grouping。
二, XSLT 2.0溶液:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*">
<xsl:for-each-group select="*/a" group-by=".">
<group type="{current-grouping-key()}">
<xsl:sequence select="current-group()/../b"/>
</group>
</xsl:for-each-group>
</xsl:template>
</xsl:stylesheet>
當在同一個XML文檔(上文)中進行這種轉化,相同的正確的結果產生:
<group type="TypeA">
<b>value1</b>
<b>value3</b>
</group>
<group type="TypeB">
<b>value2</b>
</group>
說明:
<xsl:for-each-group>
current-group()
current-grouping-key()
由於我沒有看到標題分組,我只是想澄清:你想組_and then_排序? – btlachance
非常有用的問題(和很好的答案)。我同意標題應該改寫,因爲這是一個常見問題,如果他們能夠更好地發現這個問題是他們的問題,那麼答案會對許多人感興趣。 –