Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing nodes from XDocument

Tags:

c#

xml

linq

This removes all elements from the document:

        XDocument document = XDocument.Load(inputFile);
        foreach (XElement element in document.Elements())
        {
            element.Remove();
        }
        document.Save(outputFile);

This doesn't have any effect:

        XDocument document = XDocument.Load(inputFile);
        foreach (XElement element in document.Elements())
        {
            //element.Remove();
            foreach (XElement child in element.Elements())
                child.Remove();
        }
        document.Save(outputFile);

Am I missing something here? Since these are all references to elements within the XDocument, shouldn't the changes take effect? Is there some other way I should be removing nested children from an XDocument?

Thanks!

like image 281
Jake Avatar asked Jul 09 '10 18:07

Jake


3 Answers

Apparently when you iterate over element.Elements(), calling a Remove() on one of the children causes the enumerator to yield break. Iterating over element.Elements().ToList() fixed the problem.

like image 179
Jake Avatar answered Oct 20 '22 20:10

Jake


When using XDocument try this instead:

XDocument document = XDocument.Load(inputFile);
foreach (XElement element in document.Elements())
{
     document.Element("Root").SetElementValue(element , null);
}
document.Save(outputFile)

Regards, Todd

like image 40
Raiden Flyboy Avatar answered Oct 20 '22 18:10

Raiden Flyboy


Here's an example of another way using System.Xml.XPath (change the xpath query to suit your needs):

const string xml = 
    @"<xml>
        <country>
            <states>
                <state>arkansas</state>
                <state>california</state>
                <state>virginia</state>
            </states>
        </country>
    </xml>";
XDocument doc = XDocument.Parse(xml);
doc.XPathSelectElements("//xml/country/states/state[.='arkansas']").ToList()
   .ForEach(el => el.Remove());;
Console.WriteLine(doc.ToString());
Console.ReadKey(true);
like image 20
Tahbaza Avatar answered Oct 20 '22 18:10

Tahbaza