2010-12-05 82 views
2

我想使用xslt在所有變量完全匹配時刪除重複項。如何使用xslt刪除重複的xml-節點?

在這個XML節點3應該被刪除,因爲它是節點1

<root> 
    <trips> 
     <trip> 
     <got_car>0</got_car> 
     <from>Stockholm, Sweden</from> 
     <to>Gothenburg, Sweden</to> 
     <when_iso>2010-12-06 00:00</when_iso> 
     </trip> 
     <trip> 
     <got_car>0</got_car> 
     <from>Stockholm, Sweden</from> 
     <to>New york, USA</to> 
     <when_iso>2010-12-06 00:00</when_iso> 
     </trip> 
     <trip> 
     <got_car>0</got_car> 
     <from>Stockholm, Sweden</from> 
     <to>Gothenburg, Sweden</to> 
     <when_iso>2010-12-06 00:00</when_iso> 
     </trip> 
     <trip> 
     <got_car>1</got_car> 
     <from>Test, Duncan, NM 85534, USA</from> 
     <to>Test, Duncan, NM 85534, USA</to> 
     <when_iso>2010-12-06 00:00</when_iso> 
     </trip> 
    <trips> 
<root> 
+0

可能重複[如何刪除使用XSLT重複的XML節點(http://stackoverflow.com/questions/355691/how-to-remove-duplicate-xml-nodes-using-xslt) – 2010-12-05 22:33:32

回答

1

此代碼:

<?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"/> 

<xsl:key name="trip-tth" match="/root/trips/trip" use="concat(got_car, '+', from, '+', to, '+', when_iso)"/> 

<xsl:template match="root/trips"> 
    <xsl:copy> 
     <xsl:apply-templates select="trip[generate-id(.) = generate-id(key ('trip-tth', concat(got_car, '+', from, '+', to, '+', when_iso)))]"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="trip"> 
    <xsl:copy-of select="."/> 
</xsl:template> 

</xsl:stylesheet> 

會做的伎倆。

它利用了這樣一個事實,即應用於某個鍵的generate-id()將採用匹配給定條件的第一個節點的id。在我們的案例中,標準是每個旅行子元素的串聯值。

+3

@Flack:通常你的回答不完全正確。無論何時使用連接作爲關鍵字,爲了避免將concat('A','BC')'和concat('AB','C')`'換成分隔符串是相同的」。 – 2010-12-05 22:45:47

2

有了更好的德興,這個樣式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:key name="kTripByContent" match="trip" 
      use="concat(got_car,'+',from,'+',to,'+',when_iso)"/> 
    <xsl:template match="node()|@*"> 
     <xsl:copy> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="trip[generate-id() != 
           generate-id(key('kTripByContent', 
               concat(got_car,'+', 
                from,'+', 
                to,'+', 
                when_iso))[1])]"/> 
</xsl:stylesheet> 

輸出:的

<root> 
    <trips> 
     <trip> 
      <got_car>0</got_car> 
      <from>Stockholm, Sweden</from> 
      <to>Gothenburg, Sweden</to> 
      <when_iso>2010-12-06 00:00</when_iso> 
     </trip> 
     <trip> 
      <got_car>0</got_car> 
      <from>Stockholm, Sweden</from> 
      <to>New york, USA</to> 
      <when_iso>2010-12-06 00:00</when_iso> 
     </trip> 
     <trip> 
      <got_car>1</got_car> 
      <from>Test, Duncan, NM 85534, USA</from> 
      <to>Test, Duncan, NM 85534, USA</to> 
      <when_iso>2010-12-06 00:00</when_iso> 
     </trip> 
    </trips> 
</root>