Compare two xml and print the difference using LINQ

前端 未结 3 579
我寻月下人不归
我寻月下人不归 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

    For fun, a general solution to grega g's reading of the problem. To illustrate my objection to this approach, I've introduced a "correct" entry for 'PowerShell in Action'.

    string s1 = @"
         
         
         
         
         
        ";
    string s2 = @"
         
         
         
         
         
        ";
    
    XDocument xml1 = XDocument.Parse(s1);
    XDocument xml2 = XDocument.Parse(s2);
    
    var res = from b1 in xml1.Descendants("book")
              from b2 in xml2.Descendants("book")
              let issues = from a1 in b1.Attributes()
                           join a2 in b2.Attributes()
                             on a1.Name equals a2.Name
                           select new
                           {
                               Name = a1.Name,
                               Value1 = a1.Value,
                               Value2 = a2.Value
                           }
              where issues.Any(i => i.Value1 == i.Value2)
              from issue in issues
              where issue.Value1 != issue.Value2
              select issue;
    

    Which reports the following:

    { Name = image, Value1 = C01, Value2 = C011 }
    { Name = name, Value1 = ASP.NET, Value2 = ASP.NET 2.0 }
    { Name = id, Value1 = 20507, Value2 = 20508 }
    { Name = image, Value1 = C05, Value2 = C04 }
    { Name = name, Value1 = PowerShell in Action, Value2 = Architecting Applications }
    

    Note that the last two entries are the "conflict" between the 20508 typo and the otherwise correct 20508 entry.

提交回复
热议问题