【问题标题】:What's the fastest way to find and delete duplicate nodes inside XML?在 XML 中查找和删除重复节点的最快方法是什么?
【发布时间】:2014-09-23 18:21:36
【问题描述】:

XML 文件有这样的结构

<Nodes>
   <Node> one </Node>
   <Node> two </Node>
   <Node> three </Node>
   <Node> three </Node>
</Nodes>

由于 xml 文件有超过 30000 个节点,我正在寻找最快的方法来查找和删除重复节点。

你会怎么做?

【问题讨论】:

    标签: c# .net xml linq


    【解决方案1】:

    您可以使用HashSet

    var values = new HashSet<string>();
    var xmlDocument = XDocument.Load("path");
    
    foreach(var node in xmlDocument.Root.Elements("Node").ToList())
    {
       if(!values.Add((string)node)) 
           node.Remove();
    }
    
    xmlDocument.Save("newpath");
    

    另一种方法是为XElement 类实现IEqualityComparer,然后使用Distinct 方法。

    【讨论】:

      【解决方案2】:

      尝试 XSLT 2.0 转换:

      <Nodes xmlns:xsl="http://www.w3..org/1999/XSL/Transform" xsl:version="2.0">
       <xsl:for-each-group select="/Nodes/Node" group-by=".">
        <xsl:copy-of select="current-group()[1]"/>
       </xsl:for-each-group>
      </Nodes>
      

      您可以使用 Saxon 或 XmlPrime 从 C# 运行它。

      【讨论】:

        猜你喜欢
        • 2016-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-20
        相关资源
        最近更新 更多