How can I copy an XmlNode from one XmlDocument to another?
- by Chris Wenham
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?