使用XSLT从XML文件中删除重复值
我试图使用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>
基本上我试图删除重复记录。 我如何完成这项工作?
假设所有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>
显然,如果这条字符可以是你可以在任何里面的值使用不同的字符来分隔这些值。
谢谢..这个作品很好! – sidGupta 2015-03-31 10:41:25
你可以向我解释这段代码吗?或者可以告诉我一些很好的资源,从哪里可以看到这个? – sidGupta 2015-03-31 10:43:05
要了解有关'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
你使用XSLT 1.0或2.0吗?如果某些项目(例如'title'和'artist')相同但其他不同(例如'price')会发生什么? – 2015-03-31 09:55:35
我正在使用XSLT 2.0。 – sidGupta 2015-03-31 10:05:32
现在我不考虑这种情况 – sidGupta 2015-03-31 10:07:35