简体   繁体   中英

removing all elements from xml file except root element c#

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 root element. How to accomplish this.Please help me.

XmlDocument doc = new XmlDocument();
doc.Load("filename.xml");
doc.DocumentElement.RemoveAll();
string result = doc.OuterXml;

But if you know the root node name it is pointless to load the XML and remove all elements. In this case just return the new XML:

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

or to keep the attributes on the root:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM