Merging two xml files LINQ
I have problem merging two XML files. I loaded both files into two objects, located the target nodes in both objects and tried to merge.
Here is a sample:
var nodes1 = XResult1.Descendants("subject");
var nodes2 = XResult2.Descendants("subject");
//nodes1.Add(nodes2.Nodes());
//* Code to merge** Can somebody pls help me. Thanks in advance... BB
Here is my XResult1:
<subjects> <subject> <node id="1"> Hi </node> <node id="2"> Hi again </node> <node id="3"> Hi once more </node> </subject> </subjects&开发者_StackOverflow社区gt;
Here is my XResult2 :
<subjects> <subject> <node id="4"> Hello </node> <node id="5"> Hello again </node> </subject> </subjects>
And my final Result should be :
<subjects> <subject> <node id="1"> Hi </node> <node id="2"> Hi again </node> <node id="3"> Hi once more </node> <node id="4"> Hello </node> <node id="5"> Hello again </node> </subject> </subjects>
You want to change:
XResult1.Descendants("subjects").FirstOrDefault();
XResult2.Descendants("subjects").FirstOrDefault();
to
XResult1.Descendants("subject").FirstOrDefault();
XResult2.Descendants("subject").FirstOrDefault();
Here is a more complete example:
XDocument document = XDocument.Load(@"C:\XResult1.xml");
XElement subjectElement = document.Descendants("subject").FirstOrDefault();
XDocument document2 = XDocument.Load(@"C:\XResult2.xml");
XElement subjectElement2 = document2.Descendants("subject").FirstOrDefault();
subjectElement.Add(subjectElement2.Nodes());
If you want to merge the elements inside the subject
element, you need to go down further in the tree, so set your nodes1
and nodes2
to the following:
XElement nodes2 = XResult2.Descendants("subjects").Descendants("subject").FirstOrDefault();
精彩评论