eWorld.UI - Matt Hawley

Ramblings of Matt

Copying XML Nodes from a Doc to Another

March 3, 2005 20:23 by matthaw

This should be filed as, “that’s pretty cool – I didn’t know that.” So for all of you SDK reading zealots out there, stay away - far away…I don’t want any comments (yet I have a feeling this statement will generate the fury that enrages them to post) stating “its in the SDK, just read it.” As I’ve said time and time again, when you have to work with the stuff day in and day out and only look up the stuff you need when appropriate, this theory just doesn’t work… so I don’t want to hear it, ‘kay?

So, getting away from my angst, I wanted to explain and show how you can copy (or clone) XML Nodes from one XML Document to another. This comes up if you need to generate a document based on another one, but you also need to add other items…kinda a “combination” document so-to-speak. Looking through the SDK, I noticed the ever ellusive “Clone” method, and its sister method “CloneNode”. Thinking about it, I figured – hey, that would probably work the way I want, right?

Well, partially…there’s another step you need to take to properly clone XML nodes. Prior to calling AppendChild, you need to call ImportNode on the destination XML document. This will then change it’s internal mappings to the new document. So, the code looks like:

XmlDocument doc1 = new XmlDocument();
doc1.Load(“Document1.xml”);

XmlDocument doc2 = new XmlDocument();
XmlElement docElement = doc2.CreateElement(“Document2”);
XmlElement docClone = doc2.ImportNode(doc1.SelectSingleNode(“/Document1/ToClone”).Clone(), true);

docElement.AppendChild(docClone);
doc2.AppendChild(docElement);

So, there you have it…a way to clone a node from one document to another, easily.



Categories: .NET
Actions: E-mail | Permalink | Comments (2) | Comment RSSRSS comment feed

Comments

March 3. 2005 22:38



Should the line :

docElement.AppendChild(docElement);

be

docElement.AppendChild(docClone); ?

http://

March 3. 2005 22:57

Thanks, typo in the example. Tis' fixed.

Matt Hawley

Comments are closed

Copyright © 2000 - 2024 , Excentrics World