Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
How can i delete all nodes of a XML file?

i tried this code.But gives an stack overflow error.
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
for (int i = nodes.Count - 1; i >= 0; i--)
{
    nodes[i].ParentNode.RemoveChild(nodes[i]);
}
doc.Save(path);
Posted
Comments
Tarun.K.S 24-May-11 7:19am    
Raji, can you show your xml please?
Sergey Alexandrovich Kryukov 24-May-11 15:51pm    
Why?
Please see my solution... :-)
--SA
yesotaso 24-May-11 16:07pm    
Haha, nodes[i].ParentNode.RemoveChild(nodes[i]); looks like trying "Seppuku" :P

Not exactly sure what are you trying to achieve... you could just call doc.RemoveAll() to remove all but root node (and attributes as well). If you need to delete everything, why not just delete/overwrite a file by path?
 
Share this answer
 
Here is what to do:

  • Use all your code shown in your question, then…
  • Call: doc = new XmlDocument();


Easy enough, isn't it? :-)

—SA
 
Share this answer
 
Comments
Tarun.K.S 25-May-11 2:38am    
I didn't get it.
Sergey Alexandrovich Kryukov 25-May-11 4:04am    
OK. When you delete all nodes, the data of XMLDocument carries no useful information, so, just create a new one. Isn't it logical?
--SA
Tarun.K.S 25-May-11 8:27am    
But OP isn't deleting all the nodes, only child nodes of a particular nodes.
Sergey Alexandrovich Kryukov 28-May-11 0:43am    
I don't think so. Maybe the question is formulated incorrectly, but look -- it says ***all*** XML nodes. How else should I understand it? Don't look at sample code -- this is not an answer.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900