【问题标题】:Deleting duplicate values from XML file using XSLT使用 XSLT 从 XML 文件中删除重复值
【发布时间】:2015-03-31 09:40:15
【问题描述】:

我正在尝试使用 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>

基本上我正在尝试删除重复记录。 我该怎么做?

【问题讨论】:

  • 您使用 XSLT 1.0 还是 2.0?如果某些项目(例如,titleartist)相同但其他项目不同(例如,price)会发生什么?
  • 我正在使用 XSLT 2.0。
  • 目前我不考虑这种情况

标签: xml xslt


【解决方案1】:

假设所有 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>

显然,如果该条字符可以在任何值内,您可以使用不同的字符来分隔值。

【讨论】:

  • 你能给我解释一下这段代码吗,或者告诉我一些好的资源,我可以从哪里读到这个?
  • 要了解for-each-group,请尝试任何 XSLT 2.0 书籍或教程。该规范还有一些可以提供帮助的示例:w3.org/TR/xslt20/#grouping-examples。至于上面的建议,group-by 的正常使用是对单个项目进行分组(例如group-by="title"),但是为了确保所有子项目都相同,我使用string-join(*, '|') 连接所有值,这允许我们对连接值进行分组。只要子项相同且顺序相同,就可以使用。
猜你喜欢
  • 1970-01-01
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
相关资源
最近更新 更多