Question

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>
Was it helpful?

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

OTHER TIPS

I suggest you to use LINQ to XML:

var firstDoc = XDocument.Load("file1.xml"); // load 1st file
var tagElement = XElement.Load("file2.xml"); // load <Tag> element from 2nd file
firstDoc.Root.Add(tagElement); // add <Tag> element to 1st file <Tags> element
firstDoc.Save("file1.xml"); // save 1st file
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top