本文介绍了使用linq从xml中删除重复的元素(具有特定值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这个xml
<?xml version="1.0" encoding="utf-8"?>
<super>
<A value="1234">
<a1 xx="000" yy="dddddd" />
<a1 xx="111" yy="eeeeee" />
<a1 xx="222" yy="ffffff"/>
</A>
</super>
,我需要完全删除a1元素(具有xx = 222).为什么使用我的代码不会发生这种情况?我意识到只有将它放在第一个元素的情况下它才会删除它(即,如果我要删除具有x = 000的a1,它将从第一个元素开始删除它),为什么呢?
and I need to remove a1 element (that have xx=222) completely. why this won't happen using my code?? i realized that it will delete it only if it was placed the first element(i.e, if i want to delete a1 that have x=000 , it will delete it since its the first one), why is that??
代码有什么问题?
var employee = from emp in element.Elements("A")
where (string)emp.Element("a1").Attribute("xx") == "222"
select emp.Element("a1");
foreach (var empployee_1 in employee)
{
empployee_1.Remove();
}
element.Save(@"TheLocation");
非常感谢
推荐答案
可以尝试一下吗,
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
var element = XElement.Parse(@"<?xml version=""1.0"" encoding=""utf-8""?>
<super>
<A value=""1234"">
<a1 xx=""000"" yy=""dddddd"" />
<a1 xx=""111"" yy=""eeeeee"" />
<a1 xx=""222"" yy=""ffffff""/>
</A>
</super>");
// select all the a1's that have xx = 222
var a1Elements = element.XPathSelectElement("A/a1[@xx='222']");
if (a1Elements != null)
a1Elements.Remove();
Console.WriteLine(element);
这篇关于使用linq从xml中删除重复的元素(具有特定值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!