I would like to copy a parent node and children nodes from one xml file to another. In the example below, I would like to copy Items from file #2 into file #1:
Input file #1:
<Top>
<Items>
<Item>one</Item>
<Item>two</Item>
</Items>
</Top>
Input file #2:
<Top>
<Items>
<Item>three</Item>
<Item>four</Item>
</Items>
</Top>
I want the final XML file to look like the following:
<Top>
<Items>
<Item>one</Item>
<Item>two</Item>
</Items>
<Items>
<Item>three</Item>
<Item>four</Item>
</Items>
</Top>
I attempted the following non-functional code. The InsertAfter call does not work across xml files. Any help?
XmlDocument prev = new XmlDocument(); prev.Load(filename1);
XmlDocument curr = new XmlDocument(); curr.Load(filename2);
XmlNode prev_node = prev.SelectSingleNode("Items");
XmlNode curr_node = curr.SelectSingleNode("Items");
prev.InsertAfter(curr_node, prev_node);
Many Thanks!
You can use LINQ to XML:
var prev = XDocument.Load(filename1);
var curr = XDocument.Load(filename2);
prev.Root.Add(curr.Root.Elements());