Search code examples
c#.netxmlremovechildremoveall

How to delete a child node of a parent with all their values in c# is just deleting child nodes


Hello I'm trying to delete a child node of a parent node with all their values but only is removing the child values.

I have this:

 xmldoc.Load(XMLInterfacesFile);
 XmlNode RootToDelete = xmldoc.SelectSingleNode("Servers/NEWINTERFACE");
 RootToDelete.RemoveAll();
 xmldoc.Save(XMLInterfacesFile);

My XML is :

<Servers>
  <NEWINTERFACE>
     <Host>10.10.10.2</Host>
     <Port>12</Port>
     <User>User</User>
  </NEWINTERFACE>
</Servers>

When I save the file my output is:

 <Servers>
  <NEWINTERFACE>
  </NEWINTERFACE>
</Servers>

I also want to delete element but if I select a single node "Servers" it will delete everything inside of it If I have more than 1 servers...

any idea?


Solution

  • Simply use RootToDelete.ParentNode.RemoveChild(RootToDelete);, that should do.