6

I load an XML document:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("MyFile.xml");

And also create a new document:

XmlDocument xmlDocSettings = new XmlDocument();
XmlNode xmlDecl = xmlDocSettings.CreateNode(XmlNodeType.XmlDeclaration, "", "");
xmlDocSettings.AppendChild(xmlDecl);
XmlElement root = xmlDocSettings.CreateElement("", "Test", "");
root.SetAttribute("TestAttribute", "AttributeValue");
xmlDocSettings.AppendChild(root);

Now I want to insert the content of xmlDoc to xmlDocSettings. How can I do that?

Thanks!

1 Answer 1

10

To copy content from one document to another, use Document.importNode (W3C standard, .NET implementation docs).

xmlDocSettings.DocumentElement.AppendChild(
    xmlDocSettings.ImportNode(xmlDoc.DocumentElement, true)
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I used your example, to add any node to any other node - I recommend changing the answer for the generic example: XmlDocument targetDoc = nodeToWriteOn.OwnerDocument; XmlNode nodeToAdd = targetDoc.ImportNode(node, true); nodeToWriteOn.AppendChild(nodeToAdd);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.