views:

50

answers:

4

Hello, 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.

+2  A: 

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)
Trefex
It works quite well.Thank you all.
Nano HE
+1  A: 

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.

Adkins
Nano HE
@Nano: Linq first came with .NET 3.5(?) so that could be why my answer doesn't work for you. Do you have certain requirements that limit you to 2.0? If not it could be worth looking into upgrading.
Adkins
@Adkins. Sorry for it. I updated my entry. Thank you.
Nano HE
+2  A: 

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.)

Jon Skeet
Hopefully `nodeName.ParentNode` is not `null`...
Scoregraphic
@Jon: it does exist if you are using Linq to XML. I expanded a bit on my answer to cover it.
Adkins
Nano HE
@Adkins. I added a protection like `if (node != null) { // do ...}`
Nano HE
+1  A: 

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

nodeName.ParentNode.RemoveChild(nodeName); 
unbeli