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!
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.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With