我有几个包含大量重复条目的 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>
我想删除每个子元素中的重复元素。我解决这个问题的方法是将所有元素复制到一个列表中,然后比较它们,
foreach (var el in xdoc.Descendants("annotation").ToList())
{
foreach (var x in el.Elements("image").Attributes("location").ToList())
{
//add elements to a list
}
}
进行到一半我意识到这是非常低效和耗时的。我是 XML 的新手,我想知道 C# 中是否有任何内置方法可用于删除重复项?
我试过用
if(!x.value.Distinct()) // can't convert collections to bool
x.Remove();
但这不管用,也不行
if(x.value.count() > 1) // value.count returns the number of elements.
x.Remove()
最佳答案
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();
关于c# - 有效地删除 c# 中的重复 xml 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25812456/