Removing all elements from xml file except C # root element

I have an xml file

<Abc> 
  <image filename="1.jpg" heading="1.jpg" />
  <image filename="10.jpg" heading="10.jpg" />
  <image filename="11.jpg" heading="11.jpg" />
  <image filename="2.jpg" heading="2.jpg" />
  <image filename="3.jpg" heading="3.jpg" />
</Abc>

I want to delete all elements except the root element. How to do it. Please help me.

+3
source share
3 answers
XmlDocument doc = new XmlDocument();
doc.Load("filename.xml");
doc.DocumentElement.RemoveAll();
string result = doc.OuterXml;

But if you know the root name of the node, it makes no sense to load the XML and delete all the elements. In this case, just return the new XML:

string newXml = "<rootName/>";
+2
source
    XmlDocument doc = new XmlDocument();
    doc.Load(path);
    doc.DocumentElement.RemoveAll();
    doc.Save(path);

or save attributes in the root:

    XmlNode lastChild;
    while((lastChild = root.LastChild) != null) {
        root.RemoveChild(lastChild);
    }
+2
source
 var xml = XElement.Load("xmlfile1.xml");
 xml.Descendants.Remove();
0

Source: https://habr.com/ru/post/1732811/


All Articles