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("F开发者_如何学PythonooBarBaz"), 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?
Take a look at XmlDocument.ImportNode.
Check out the ImportNode method:
var myNewDoc = new XmlDocument();
myNewDoc.ImportNode(xmlNode, true);
精彩评论