简体   繁体   中英

Comparing two XML files with IEnumerable.Except()

With the following code:

    XDocument aDoc = XDocument.Load(fileA);
    XDocument bDoc = XDocument.Load(fileB);

    var commonfromA = aDoc.Descendants("Project").Except(bDoc.Descendants("Project")); 

I compare the following XML:

aDoc.xml

<Employees>
      <Project ID="1" Name="Project1"/>
      <Project ID="2" Name="Project2"/>
</Employees>

bDoc.xml

<Employees>
  <Project ID="1" Name="Project1"/>
  <Project ID="3" Name="Project3"/>
</Employees> 

When I execute the code I obtain

<Project ID="1" Name="Project1"/>
<Project ID="2" Name="Project2"/>

Rather than

<Project ID="2" Name="Project2"/> **Which is the elements that are in A but not in B**

Thank you in advance.

Yes, that's because none of the elements in aDoc are actually in bDoc. If you ask each of those elements for its parents, they will report different results.

If you're happy just getting the IDs, it's easy:

var idsJustInA = aDoc.Descendants("Project")
                     .Select(x => (int) x.Attribute("ID"))
                     .Except(bDoc.Descendants("Project"))
                                 .Select(x => (int) x.Attribute("ID")));

If you want the elements themselves, you could either pass an IEqualityComparer<XElement> to compare elements by ID, or you could use something like ExceptBy from MoreLINQ :

var justInA = aDoc.Descendants("Project")
                  .ExceptBy(bDoc.Descendants("Project"),
                            x => (int) x.Attribute("ID"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM