Saturday, May 9, 2009

How to merge 2 XmlDocuments

Hi,
In this post i'll show u how 2 merge 2 xml documents
let's say that i have 2 xml documents,

Persons.xml

<?xml version='1.0'?>

<Persons>

<Person Height="180">

<FullName>Yosi Havia</FullName>

<Age>18</Age>

</Person>

<Person Height="177">

<FullName>Yosi Cohen</FullName>

<Age>22</Age>

</Person>

<Person Height="169">

<FullName>Itay Cohen</FullName>

<Age>32</Age>

</Person>

</Persons>



and Persons2.xml

<?xml version='1.0'?>

<Persons>

<Person Height="175">

<FullName>Yosi Havia</FullName>

<Age>15</Age>

</Person>

</Persons>



What i want 2 do in this example is 2 take the node with the full name 'Yosi Havia' from Persons2.xml file and replace the original node with the same full name in Persons.xml file.
this code lines make this assigment(with help of my last post Simple XPath Examples ):

XmlDocument XmlPersons1 = new XmlDocument();
XmlPersons1.Load(@"Persons.xml");

XmlDocument XmlPersons2 = new XmlDocument();
XmlPersons2.Load(@"Persons2.xml");

XmlNode oXmlNewData = XmlPersons2.SelectSingleNode("/Persons/Person[FullName = '" + "Yosi Havia" + "']");
XmlNode targetNode = XmlPersons1.SelectSingleNode("/Persons/Person[FullName = '" + "Yosi Havia" + "']");
//@@@ Add the node from XmlPersons2.xml to XmlPersons.xml
XmlNode sourceNode = XmlPersons1.ImportNode(oXmlNewData, true);
//@@@ Replace the original node
XmlPersons1.DocumentElement.ReplaceChild(sourceNode, targetNode);

and u can c the result here:

<?xml version="1.0"?>

<Persons>

<Person Height="175">

<FullName>Yosi Havia</FullName>

<Age>15</Age>

</Person>

<Person Height="177">

<FullName>Yosi Cohen</FullName>

<Age>22</Age>

</Person>

<Person Height="169">

<FullName>Itay Cohen</FullName>

<Age>32</Age>

</Person>

</Persons>

2 comments:

msqr said...

Have you tried this?
xDoc1.ImportNode(xDoc2)

Yosi Havia said...

Hi msqr,
no, i did not
what's the results?