Link to home
Start Free TrialLog in
Avatar of Johny Bravo
Johny Bravo

asked on

Merge Xml files in c#

Hi Experts,

I need to merge two xml files, having lack of experience with xml I am struggling here.

I have two xml files. One is original file and second xml file contains new updates to be made in original xml.

This is the original file. file1.xml

Now I have a new xml which contains new update to be done in first xml, please check file2.xml

Now I want to update first xml with the changes available in second xml, so the final xml should look like,
Output.xml

So basically my second xml contains only the changes to be added/ updated in original xml. I believe this should be easy for an expert. (By mistake I types hard earlier :)
Your help here is really appreciated.

Thanks
SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Johny Bravo
Johny Bravo

ASKER

Hi AndyAinscow

Thanks for the links. I edited question, I didn't mean hard :)

Reading and writing is easy when I know where to writein xml.
But here I want to check new xml, check the nodes, find the same structure in first xml andthen add/ update.
If you can provide me a sample code that would be much better to understand.
Thanks
var doc = XDocument.Load(path);
                var doc2 = XDocument.Load("C:/Users/file2.xml");
                var children = doc2.Root.Element("SPaper");
                var parentNode = doc.Root.Element("SPaper");
               // parentNode.ReplaceWith(children);

var combinedUnique = doc.Descendants("SPaper")
                          .Union(doc2.Descendants("SPaper"));

Open in new window

(combinedUnique.ToList())[0] //give me xml in 1st file
(combinedUnique.ToList())[1] //give me xml in 2nd file

How to write merged result in 1st xml?
Your combinedUnique should be an XMLDocument - just save it to the file file name and path to overwrite the first file.  (See my earlier link re writing)
But this will create file only with merged xml, I need to replace first file content with updates in new file. It will not give me the desired o/p which I have shared in my final xml
From my first comment:
adding new elements, replacing existing elements.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That should accomplish what was requested