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

10,548

Solution 1

Take a look at XmlDocument.ImportNode.

Solution 2

Check out the ImportNode method:

var myNewDoc = new XmlDocument();
myNewDoc.ImportNode(xmlNode, true);
Share:
10,548
Ajibola
Author by

Ajibola

Updated on June 13, 2022

Comments

  • Ajibola
    Ajibola almost 2 years

    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?