如果我有这个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,它将从第一个删除它),为什么会这样?
代码有什么问题??
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");
非常感谢
答案 0 :(得分:1)
你能试试吗,
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);
答案 1 :(得分:1)
试试这个
IEnumerable<XElement> element = from element1 in doc.Elements("A") select element1;
foreach (XElement xe in element.Elements())
{
if (xe.Attribute("xx").Value == "222")
xe.Remove();
}