Reputation: 4001
If I have this 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>
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??
what wrong with the code ??
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");
thanks alot
Upvotes: 0
Views: 804
Reputation: 1627
try this
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();
}
Upvotes: 1
Reputation: 32768
Can you try this,
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);
Upvotes: 1