有效删除c#中的重复xml元素

cyb*_*mon 1 c# xml

我有几个包含大量重复条目的XML文件,例如这些.

<annotations>
  <annotation value=",Clear,Outdoors" eventID="2">
    <image location="Location 1" />
    <image location="Location 2" />
    <image location="Location 2" />
  </annotation>

  <annotation value=",Not a problem,Gravel,Shopping" eventID="2">
    <image location="Location 3" />
    <image location="Location 4" />
    <image location="Location 5" />
    <image location="Location 5" />
    <image location="Location 5" />
  </annotation>
</annotations>
Run Code Online (Sandbox Code Playgroud)

我想删除每个子节点中的重复元素.我接近这个的方法是将所有元素复制到列表然后比较它们,

 foreach (var el in xdoc.Descendants("annotation").ToList())
   {
      foreach (var x in el.Elements("image").Attributes("location").ToList())
       {
           //add elements to a list
       }
   }
Run Code Online (Sandbox Code Playgroud)

一半我意识到这是非常低效和耗时的.我对XML很新,我想知道C#中是否有任何内置方法可以用来删除重复项?

我试过用

if(!x.value.Distinct()) // can't convert collections to bool
    x.Remove();
Run Code Online (Sandbox Code Playgroud)

但这不起作用,也不起作用

if(x.value.count() > 1) // value.count returns the number of elements.
   x.Remove()
Run Code Online (Sandbox Code Playgroud)

Ton*_*ark 6

using System.Xml.Linq;

XDocument xDoc = XDocument.Parse(xmlString);
xDoc.Root.Elements("annotation")
         .SelectMany(s => s.Elements("image")
                           .GroupBy(g => g.Attribute("location").Value)
                           .SelectMany(m => m.Skip(1))).Remove();
Run Code Online (Sandbox Code Playgroud)