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

I am creating a tool that author / edits XML files, and I want it to be able to fill it with template fragments defined in another XML file.

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

Or say this is my template file:

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

Then I can capture the template fragment with .GetElementsByTagName ("FooBarBaz"), and I would like to be able to enter it into a new document with something like .AppendChild (templateNode).

But the problem is that the 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 a different context.

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

+4
source share
2 answers

Take a look at XmlDocument.ImportNode .

+7
source

Check out the ImportNode method:

 var myNewDoc = new XmlDocument(); myNewDoc.ImportNode(xmlNode, true); 
+3
source

Source: https://habr.com/ru/post/1303965/


All Articles