Search code examples
c#xmldocument

Removing a child node from XmlNode


I am using XPath to select a report node. Now what I want to know here is how can I remove that node from the document without knowing which node's children they are?

I tried calling .RemoveChild and it throws this error :

The node to be removed is not a child of this node.

This is my code for deleting a node :

var node = doc.SelectSingleNode("//report");
doc.RemoveChild(node);

Solution

  • You can get know the parent node:

    node.ParentNode.RemoveChild(node);
    

    Please note that the node.ParentNode can be null.