How to merge two XmlDocuments in C#

后端 未结 4 872
半阙折子戏
半阙折子戏 2020-12-14 17:33

I want to merge two XmlDocuments by inserting a second XML doc to the end of an existing Xmldocument in C#. How is this done?

4条回答
  •  既然无缘
    2020-12-14 17:48

    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
    
    

提交回复
热议问题