tags:

views:

46

answers:

2

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!

+1  A: 

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);
Tahbaza
+1  A: 

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.

Jake