Search code examples
c#xmlxmldocument

Add XmlDocument in XmlDocument


hi i have xml files and i need to append them like this:

First File:

<Tags>
    <Tag name ="1">
        //more xml tags
    </Tag>

    <Tag name = "2">
        //some more xml tags

    </Tag>

    .....

    //add second file here

</Tags>

Second File:

 <Tag name ="3">
     //more xml tags
 </Tag>

Solution

  • Use ImportNode method:

    var d1 = new XmlDocument();
    d1.LoadXml("<Tags><Tag name =\"1\"></Tag></Tags>");
    
    var d2 = new XmlDocument();
    d2.LoadXml("<Tags><Tag name =\"2\"></Tag></Tags>");
    
    var newNode = d1.ImportNode(d2.SelectSingleNode("/Tags/Tag"), true);
    d1.DocumentElement.AppendChild(newNode);
    
    Console.WriteLine(d1.OuterXml);
    

    Here is the fiddle