XmlNode.ReplaceChild complains that the node I'm trying to delete is not a child, despite the fact that I got to the node through ParentNode

I have a simple function that is designed to copy a section of an XML document to another. I want to replace one node with another, so ReplaceChild seems like a logical choice. I keep getting the error "The node link is not a child of this node." though. This seems odd since I found that node by asking the parent first. Any idea what I'm doing wrong?

private static void KeepSection(XmlDocument newDoc, XmlDocument currentDoc, XmlNamespaceManager nsmgr, string path) { XmlNode section = currentDoc.SelectSingleNode(path, nsmgr); XmlNode newSection = newDoc.SelectSingleNode(path, nsmgr); if (newSection != null && section != null) { XmlNode parent = newSection.ParentNode; parent.ReplaceChild(newSection, newDoc.ImportNode(section, true)); } } 
+4
source share
2 answers

It looks like you changed the ReplaceChild options:

 public virtual XmlNode ReplaceChild( XmlNode newChild, XmlNode oldChild ) 
+6
source

Actually, I was an idiot. I got the ReplaceChild options, if I'm not mistaken. The code should have been

  parent.ReplaceChild(newDoc.ImportNode(section, true), newSection); 

Sorry for that!

0
source

All Articles