2015-03-31 91 views
0

我試圖使用XSLT從XML文件中刪除重複項。 輸入是這樣的:使用XSLT從XML文件中刪除重複值

<catalog> 
<cd> 
    <title>Empire Burlesque</title> 
    <artist>Bob Dylan</artist> 
    <country>USA</country> 
    <company>Columbia</company> 
    <price>10.90</price> 
    <year>1985</year> 
</cd> 
<cd> 
    <title>Hide your heart</title> 
    <artist>Bonnie Tyler</artist> 
    <country>UK</country> 
    <company>CBS Records</company> 
    <price>9.90</price> 
    <year>1988</year> 
</cd> 
    <cd> 
    <title>Hide your heart</title> 
    <artist>Bonnie Tyler</artist> 
    <country>UK</country> 
    <company>CBS Records</company> 
    <price>9.90</price> 
    <year>1988</year> 
</cd> 

所需的輸出是:

<catalog> 
<cd> 
    <title>Empire Burlesque</title> 
    <artist>Bob Dylan</artist> 
    <country>USA</country> 
    <company>Columbia</company> 
    <price>10.90</price> 
    <year>1985</year> 
</cd> 
<cd> 
    <title>Hide your heart</title> 
    <artist>Bonnie Tyler</artist> 
    <country>UK</country> 
    <company>CBS Records</company> 
    <price>9.90</price> 
    <year>1988</year> 
</cd> 

基本上我試圖刪除重複記錄。 我如何完成這項工作?

+0

你使用XSLT 1.0或2.0嗎?如果某些項目(例如'title'和'artist')相同但其他不同(例如'price')會發生什麼? – 2015-03-31 09:55:35

+0

我正在使用XSLT 2.0。 – sidGupta 2015-03-31 10:05:32

+0

現在我不考慮這種情況 – sidGupta 2015-03-31 10:07:35

回答

0

假設所有cd元素都以相同的順序和酒吧字符|相同的子元素沒有任何價值的一部分,你可以使用

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    exclude-result-prefixes="xs"> 

<xsl:output indent="yes"/> 

<xsl:template match="/*"> 
    <xsl:copy> 
    <xsl:for-each-group select="cd" group-by="string-join(*, '|')"> 
     <xsl:copy-of select="."/> 
    </xsl:for-each-group> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 

顯然,如果這條字符可以是你可以在任何裏面的值使用不同的字符來分隔這些值。

+0

謝謝..這個作品很好! – sidGupta 2015-03-31 10:41:25

+0

你可以向我解釋這段代碼嗎?或者可以告訴我一些很好的資源,從哪裏可以看到這個? – sidGupta 2015-03-31 10:43:05

+0

要了解有關'for-each-group',請嘗試使用任何XSLT 2.0書籍或教程。該規範也有一些例子可以幫助:http://www.w3.org/TR/xslt20/#grouping-examples。至於上面的建議,'group-by'的正常使用是在一個單獨的項目上進行分組(例如'group-by =「title」'),但是如果你想確保所有的子項目都是我用過的'string-join(*,'|')'連接所有的值,這允許我們對連接值進行分組。只要子項是相同的並且按照相同的順序工作。 – 2015-03-31 10:48:26