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

Posted by Chris Wenham on Stack Overflow See other posts from Stack Overflow or by Chris Wenham
Published on 2010-03-12T18:32:31Z Indexed on 2010/03/12 18:37 UTC
Read the original article Hit count: 229

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about .net-3.5

Related posts about .net-4.0