TestFile

Remove xml nodes from XML document

I have an XMLDocument like:

<Folder name="test"> <Folder name="test2"> <File>TestFile</File> </Folder> </Folder> 

I want only folders, not files. So how to delete / process an XML document in C # to remove / delete ALL elements in a document?

Thanks!

+4
source share
2 answers

If you can use XDocument and LINQ, you can do

 XDocument doc = XDocument.Load(filename) // or XDocument.Parse(string) doc.Root.Descendants().Where(e => e.Name == "File").Remove(); 

- error edited

+3
source

To remove node from XMLDocument (see Jens answer for removing node form XDocument )

 XmlDocument doc = XmlDocument.Load(filename); // or XmlDocument.LoadXml(string) XmlNodeList nodes = doc.SelectNodes("//file"); foreach(XmlNode node in nodes) { node.ParentNode.RemoveChild(node); } 

Watch out for a possible possible exception if node.ParentNode is null.

+2
source

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


All Articles