Question

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!

Was it helpful?

Solution

You can use LINQ to XML:

var prev = XDocument.Load(filename1);
var curr = XDocument.Load(filename2);
prev.Root.Add(curr.Root.Elements());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top