Compare two xml and print the difference using LINQ

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

    Here is the solution:

    //sanitised xmls:
    string s1 = @"
                     
                     
                     
                     
                    ";
    string s2 = @"
                      
                      
                      
                      
                    ";
    
    XDocument xml1 = XDocument.Parse(s1);
    XDocument xml2 = XDocument.Parse(s2);
    
    //get cartesian product (i think)
    var result1 =   from xmlBooks1 in xml1.Descendants("book")
                    from xmlBooks2 in xml2.Descendants("book")
                    select new { 
                                book1 = new {
                                            id=xmlBooks1.Attribute("id").Value,
                                            image=xmlBooks1.Attribute("image").Value,
                                            name=xmlBooks1.Attribute("name").Value
                                          }, 
                                book2 = new {
                                            id=xmlBooks2.Attribute("id").Value,
                                            image=xmlBooks2.Attribute("image").Value,
                                            name=xmlBooks2.Attribute("name").Value
                                          } 
                                 };
    
    //get every record that has at least one attribute the same, but not all
    var result2 = from i in result1
                     where (i.book1.id == i.book2.id 
                            || i.book1.image == i.book2.image 
                            || i.book1.name == i.book2.name) &&
                            !(i.book1.id == i.book2.id 
                            && i.book1.image == i.book2.image 
                            && i.book1.name == i.book2.name) 
                     select i;
    
    
    
    foreach (var aa in result2)
    {
        //you do the output :D
    }
    

    Both linq statements probably could be merged, but I leave that as an exercise for you.

提交回复
热议问题