tags:

views:

263

answers:

2

I have a simple function that's designed to copy a section of an xml document to another. I want to replace one node with the other so ReplaceChild seems like the logical choice. I keep getting the error 'The reference node is not a child of this node.' though. That seems odd since I found that node by asking for the parent in the first place. 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));
        }
    }
A: 

It looks like you have your ReplaceChild parameters reversed:

public virtual XmlNode ReplaceChild(
    XmlNode newChild,
    XmlNode oldChild
)
Andy West
A: 

Actually I was being an idiot. I got the parameters to ReplaceChild the wrong way around. The code should have been,

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

Sorry about that!

Colin Newell
I wouldn't say you were being an idiot - I think the parameter ordering is not intuitive. :-)
Andy West
ha! i just made the same mistake! lost a solid 10 minutes scratching my head.
Andrew Garrison