Smartssolutions

Wednesday, May 25, 2011

Merge Two Xml Files using Linq and C#

Here is a code that helps megre two distincts Xml files thoses have the same structure

using System;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Diagnostics;
using System.IO;
namespace MSDN
{
  class Program
  { 
    static void Main(string[] args)
    {
      
      XDocument doc1 = XDocument.Load(@"C:\temp\config1.xml");
      XDocument doc2 = XDocument.Load(@"C:\temp\config2.xml");

      var query1 = from el 
              in doc2.Elements().Except(doc1.Elements()) 
            select el;
      var query2 = from el
              in doc1.Elements().Except(doc2.Elements())
             select el;

      var query = query2.Except(query1);
      
      foreach (var item in query)
      {
        Console.WriteLine(item);
      }
      Console.ReadLine();
    }

  }
}
 
You have to add two config files to the C:\temp directory. They should be differents. The result will give you a resulting of the both configurations.
try to change doc1 by doc2 within quey1 and query2 and vice versa try to swap query1 and query2 in the query to find out the suitable cmbination for update for you 

No comments:

Post a Comment