這是一個常見問題。見http://www.jenitennison.com/xslt/grouping/muenchian.html
該XSLT代碼:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="UTF-8"/>
<xsl:key name="criteria" match="/Nodes/Node" use="@att"/>
<xsl:template match="Nodes">
<xsl:copy>
<xsl:apply-templates select="Node[generate-id() = generate-id(key('criteria', @att))]"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Node">
<xsl:copy-of select="."/> <!-- Or other actions -->
</xsl:template>
</xsl:stylesheet>
將提供所需的(如果我理解正確的)輸出:
<?xml version="1.0" encoding="UTF-8"?>
<Nodes>
<Node att="1">A</Node>
<Node att="2">C</Node>
<Node att="3">E</Node>
</Nodes>
它也將與像輸入工作,例如:
<Nodes>
<Node att="someRandomString">A</Node>
<Node att="1aeawe">B</Node>
<Node att="someRandomString">C</Node>
<Node att="sfdf">D</Node>
<Node att="">E</Node>
<Node att="sfdf">F</Node>
</Nodes>
輸出結果爲:
<?xml version="1.0" encoding="UTF-8"?>
<Nodes>
<Node att="someRandomString">A</Node>
<Node att="1aeawe">B</Node>
<Node att="sfdf">D</Node>
<Node att="">E</Node>
</Nodes>
這裏有一個非常類似的問題,有很多答案:http://stackoverflow.com/questions/399204/xslt-distinct-elements-and-分組 – 2010-12-10 23:03:27
「ACE」輸出將用於每個獨立值的第一個(文檔順序)。請做澄清。 – 2010-12-10 23:05:30
好問題,+1。查看我的答案可能是最簡單和最短的解決方案 - XPath單行程式。 :) – 2010-12-11 00:10:57