2015-12-04 169 views
1

我試圖刪除具有相同href屬性的元素構成本文件:使用此XSLT 2.0樣式表XSLT刪除重複的元素

<?xml version="1.0" encoding="UTF-8"?> 
<images> 
    <item id="d1e152_1" href="Pic/104764.jpg" media-type="image/jpeg"/> 
    <item id="d1e163_2" href="Pic/104764.jpg" media-type="image/jpeg"/> 
    <item id="d1e174_3" href="Pic/104764.jpg" media-type="image/jpeg"/> 
    <item id="d1e218_4" href="Pic/104763.jpg" media-type="image/jpeg"/> 
    <item id="d1e349_5" href="Pic/110001.tif" media-type="image/tif"/> 
    <item id="d1e681_6" href="Pic/199201.tif" media-type="image/tif"/> 
    <item id="d1e688_7" href="Pic/124566.tif" media-type="image/tif"/> 
</images> 

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" exclude-result-prefixes="fn xs fo"> 

<xsl:output method="xml"/> 

<xsl:strip-space elements="*"/> 

<xsl:template match="/images"> 
<new_images> 
    <xsl:apply-templates/> 
    </new_images> 
</xsl:template> 

<xsl:template match="item"> 
<xsl:for-each-group select="." group-by="@href"> 
    <xsl:copy-of select="current-group()[1]"/> 
</xsl:for-each-group> 
</xsl:template> 

</xsl:stylesheet> 

預期結果在這裏:

<?xml version="1.0" encoding="UTF-8"?> 
<new_images> 
    <item id="d1e152_1" href="Pic/104764.jpg" media-type="image/jpeg"/> 
    <item id="d1e218_4" href="Pic/104763.jpg" media-type="image/jpeg"/> 
    <item id="d1e349_5" href="Pic/110001.tif" media-type="image/tif"/> 
    <item id="d1e681_6" href="Pic/199201.tif" media-type="image/tif"/> 
    <item id="d1e688_7" href="Pic/124566.tif" media-type="image/tif"/> 
</new_images> 

爲什麼不能正常工作?我仍然在生成的xsl文件中有所有重複項。

回答

1

該XSLT 1.0溶液較短並且不慢:

<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="kByHref" match="item" use="@href"/> 

    <xsl:template match="/*"> 
    <new_images> 
     <xsl:copy-of select= 
     "*[generate-id() = generate-id(key('kByHref', @href)[1])]"/> 
    </new_images> 
    </xsl:template> 
</xsl:stylesheet> 
+0

非常感謝! – user3813234

+0

@ user3813234,不客氣。 –

1

我得到它....發生在我身上所有的時間......得把該換的每個組中的模板/圖像...

更新XSLT 2.0 ...

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" exclude-result-prefixes="fn xs fo"> 

    <xsl:output method="xml"/> 

    <xsl:strip-space elements="*"/> 

    <xsl:template match="/images"> 
    <new_images> 
     <xsl:for-each-group select="item" group-by="@href"> 
     <xsl:copy-of select="current-group()[1]"/> 
     </xsl:for-each-group> 
    </new_images> 
    </xsl:template> 

</xsl:stylesheet> 
+0

user3813234,有一個** XSLT 1.0 **解決方案更短,更簡單的顯著和至少同樣有效的XSLT 2.0解決方案帽子使用'' - 查看我的答案。 –