Question

When I try to remove some of my child element with RemoveChild(). But throw exception. I attached my code below.

    nodeName = doc.SelectSingleNode("//Equipment//DataCollections//EnabledIDs//MyID[@id='" + attrValue + "']"); 
   // Found the nodeName successfully druing run time.
    doc.DocumentElement.RemoveChild(nodeName); 
   // faild to Remove the node

Show error below:

An unhandled exception of type 'System.ArgumentException' occurred in System.Xml.dll

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

How can I remove the node?

[Update]

VS2005 & .NET 2.0 used.

Was it helpful?

Solution

I believe .RemoveChild is removing the child of the node you selected.

Are there any children under nodeName or is it the leaf already?

Edit:

Actually you need to remove the Child of the Parent, try the following:

nodeName.parentNode.removeChild(nodeName)

OTHER TIPS

You're trying to remove a node directly from the document element, when it's actually a great-grandchild of the document element (or maybe just a grandchild). RemoveChild only works when you specify a direct child, not just any descendant.

Try this:

nodeName.ParentNode.RemoveChild(nodeName);

(If Remove() exists as per Adkins' answer, that would be better - but I can't find such a method in MSDN.)

You should remove child from the immediate parent, not from the top:

nodeName.ParentNode.RemoveChild(nodeName); 

Instead of using .RemoveChild try just using .Remove That should give you the outcome you are looking for.

Edit::

Note that this only works if you are using Linq to XML. Then you would be working with some variation of an XNode and can simply say blah.Remove and it should do the trick. If you are not using Linq to XML I would suggest looking into that cause it is amazing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top