Removing xml nodes...why is it so complicated

R

RC

Hi,
From the following xmldocument, I want to remove all the badapple xml
nodes..It looks like it is not straight forward .NET 2.0 using
xmldocument and xpath

Input:
<xml>
<Fruits>
<Apple Color = "Red"/>
<Apple Color = "Blue">
<BadApple><Apple Color = "White"/></BadApple>
<BadApple><Apple Color = "Green"/></BadApple>
<Apple Color = "Maroon">
</Fruits>
</xml>

Output:
<xml>
<Fruits>
<Apple Color = "Red"/>
<Apple Color = "Blue">
<Apple Color = "Maroon">
</Fruits>
</xml>

thanks in advance..
 
M

Marc Gravell

The usual problem of changing the list you are enumerating...

how about:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<xml><Fruits><Apple Color = \"Red\"/><Apple Color
= \"Blue\"/><BadApple><Apple Color =
\"White\"/></BadApple><BadApple><Apple Color =
\"Green\"/></BadApple><Apple Color = \"Maroon\"/></Fruits></xml>");
List<XmlElement> remove = new List<XmlElement>();
foreach (XmlElement el in doc.GetElementsByTagName("BadApple"))
{
remove.Add(el);
}
foreach (XmlElement el in remove) {
el.ParentNode.RemoveChild(el);
}
Console.WriteLine(doc.OuterXml);

Note I used GetElementsByTagName, but a SelectNodes implementation
would have been otherwise identical.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top