什么是找到并删除里面的XML重复节点最快的方法是什么?节点、里面、最快、方法

2023-09-04 05:44:21 作者:年华何日不离伤

XML文件中有这样的结构

XML file has structure like this

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

由于XML文件有超过30000的节点我在找最快的方式找到并删除重复的节点。

Since xml file has more than 30000 nodes I'm looking for fastest way to find and delete duplicate nodes.

你会怎么做呢?

推荐答案

您可以使用的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");

另一种方法是实施的IEqualityComparer 的XElement 类,然后使用分明方法。

Another way is to implement an IEqualityComparer for XElement class then use Distinct method.