Daniel Camacho
Daniel Camacho

Reputation: 423

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.

Upvotes: 2

Views: 1257

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502286

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"));

Upvotes: 1

Related Questions