Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy an XmlNode from one XmlDocument to another?

I'm building a tool that authors/edits XML files, and I want to be able to populate it with template fragments defined in another XML file.

For example, the tool has an "Add FooBarBaz Element" button that adds a element to the new document being created, and I want to add FooBarBaz by copying it from a template.

Or let's say this is my template file:

<Templates>
    <FooBarBaz Attribute="Value">
        <ChildElement/>
    </FooBarBaz>
</Templates>

I can then grab a template fragment with .GetElementsByTagName("FooBarBaz"), and I'd like to be able to inject it into the new document with something like .AppendChild(templateNode).

But the problem is that an XmlNode cannot be copied from one XmlDocument to another, even if you use .Clone() or .CloneNode(), because AppendChild() throws an exception saying that the template element belongs to another context.

Is there an easy way to copy a System.Xml.XmlNode between System.Xml.XmlDocuments?

like image 278
Chris Wenham Avatar asked Mar 12 '10 18:03

Chris Wenham


2 Answers

Take a look at XmlDocument.ImportNode.

like image 65
dkackman Avatar answered Nov 18 '22 11:11

dkackman


Check out the ImportNode method:

var myNewDoc = new XmlDocument();
myNewDoc.ImportNode(xmlNode, true);
like image 30
Adam Lear Avatar answered Nov 18 '22 12:11

Adam Lear