I want to merge two XmlDocument
s by inserting a second XML doc to the end of an existing Xmldocument
in C#. How is this done?
Inserting an entire XML document at the end of another XML document is actually guaranteed to produce invalid XML. XML requires that there be one, and only one "document" element. So, assuming that your files were as follows:
A.xml
value1
value2
B.xml
value3
value4
The resultant document by just appending one at the end of the other:
value1
value2
value3
value4
Is invalid XML.
Assuming, instead, that the two documents share a common document element, and you want to insert the children of the document element from B into A's document element, you could use the following:
var docA = new XmlDocument();
var docB = new XmlDocument();
foreach (var childEl in docB.DocumentElement.ChildNodes) {
var newNode = docA.ImportNode(childEl, true);
docA.DocumentElement.AppendChild(newNode);
}
This will produce the following document given my examples above:
value1
value2
value3
value4