Wednesday, July 11, 2012

XmlDocument Class ImportNode() method

The XmlDocument.ImportNode() method is probably one of the most misunderstood function in the XmlDocument class in C# (.NET). Programmers probably expects the function to import a set of nodes from one XML document instance to another instance and place the nodes inside the target XML document instance. However, that's not what happened. Reading from MSDN (http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.importnode.aspx):
Importing a node creates an XmlNode object owned by the importing document, with Name and NodeType identical to the source node. The new object also has the attributes related to namespaces (Prefix, LocalName, and NamespaceURI).
After reading the statement at MSDN above, what you should be aware is the ImportNode() method doesn't place the imported set of node in the target XML document. The method merely import the set of node from the context of the source XML document to the target XML document. What I mean by context here have to do with XML namespace. You cannot just place a "rogue" set of nodes without namespace in the target XML document, you have to give a context to the set of nodes, i.e. valid XML namespace, etc. In most cases this is probably what you want to do:
                
foreach (XmlNode currentNode in facts.DocumentElement.ChildNodes)
{
    node = doc.ImportNode(facts.DocumentElement.ChildNodes.Item(i), true);
    doc.DocumentElement.AppendChild(node);
    i++;
}

The code above copies every single child element of the root element of the facts XmlDocument object (source) to the doc XmlDocument (destination) root element.

So, next time you deal with the ImportNode() method, remember that what it does is related to the XML document instance context.
Post a Comment

1 comment:

Unknown said...

Thanks for the post. I also expected ImportNode() to go all the way of "importing" node.