Compare two xml and print the difference using LINQ

前端 未结 3 542
我寻月下人不归
我寻月下人不归 2021-01-02 11:38

I am comparing two xml and I have to print the difference. How can I achieve this using LINQ. I know I can use XML diff patch by Microsoft but I prefer to use LINQ . If you

3条回答
  •  时光取名叫无心
    2021-01-02 12:25

    The operation you want here is a Zip to pair up corresponding elements in your two sequences of books. That operator is being added in .NET 4.0, but we can fake it by using Select to grab the books' indices and joining on that:

    var res = from b1 in xml1.Descendants("book")
                             .Select((b, i) => new { b, i })
              join b2 in xml2.Descendants("book")
                             .Select((b, i) => new { b, i })
                on b1.i equals b2.i
    

    We'll then use a second join to compare the values of attributes by name. Note that this is an inner join; if you did want to include attributes missing from one or the other you would have to do quite a bit more work.

              select new
              {
                  Row = b1.i,
                  Diff = from a1 in b1.b.Attributes()
                         join a2 in b2.b.Attributes()
                           on a1.Name equals a2.Name
                         where a1.Value != a2.Value
                         select new
                         {
                             Name = a1.Name,
                             Value1 = a1.Value,
                             Value2 = a2.Value
                         }
              };
    

    The result will be a nested collection:

    foreach (var b in res)
    {
        Console.WriteLine("Row {0}: ", b.Row);
        foreach (var d in b.Diff)
            Console.WriteLine(d);
    }
    

    Or to get multiple rows per book:

    var report = from r in res
                 from d in r.Diff
                 select new { r.Row, Diff = d };
    
    foreach (var d in report)
        Console.WriteLine(d);
    

    Which reports the following:

    { Row = 0, Diff = { Name = image, Value1 = C01, Value2 = C011 } }
    { Row = 1, Diff = { Name = name, Value1 = ASP.NET, Value2 = ASP.NET 2.0 } }
    { Row = 3, Diff = { Name = id, Value1 = 20507, Value2 = 20508 } }
    

提交回复
热议问题