cw.
cw.

Reputation: 133

LINQ to XML Query Help

I am trying to get a "diff" of 2 xml documents and end up with a list of Elements that are different. Below is the XML, I was wondering if anyone can assist. In the case below, I want the list to contain the "file2.xml" element and the "file3.xml" element because they are both different or new than the first xml document.

Thanks in advance!

<?xml version="1.0" encoding="utf-8" ?>
<versioninfo>
  <files>
    <file version="1.0">file1.xml</file>
    <file version="1.0">file2.xml</file>
  </files>
</versioninfo>


<?xml version="1.0" encoding="utf-8" ?>
<versioninfo>
  <files>
    <file version="1.0">file1.xml</file>
    <file version="1.1">file2.xml</file>
    <file version="1.0">file3.xml</file>
  </files>
</versioninfo>

Upvotes: 1

Views: 96

Answers (1)

Aaronaught
Aaronaught

Reputation: 122624

I believe that what you're trying to do is get a list of all the file names that have different versions. If so, this would do it:

XDocument first = (...);
XDocument second = (...);

var firstFiles = first.Element("versioninfo").Element("files").Elements("file");
var secondFiles = second.Element("versioninfo").Element("files").Elements("file");

var changedFileNames =
    from f1 in firstFiles
    join f2 in secondFiles
        on f2.Value equals f1.Value
    where f1.Attribute("version").Value != f2.Attribute("version").Value
    select f1.Value;

var firstFileNames = firstFiles.Select(f => f.Value);
var secondFileNames = secondFiles.Select(f => f.Value);
var addedFileNames = firstFileNames.Except(secondFileNames);
var removedFileNames = secondFileNames.Except(firstFileNames);

var allChanges = changedFileNames
    .Concat(addedFileNames)
    .Concat(removedFileNames);

Upvotes: 1

Related Questions