tags:

views:

44

answers:

1

Hello,

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>
+1  A: 

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);
Aaronaught
But also the ones in one list but not the other, so your answer is half the solution.
Simon Thompson
Good points, should have read the question more carefully; I've updated this to include added/removed files.
Aaronaught
it is half, missing ones that "arent" in the original list
cw
@cw: It's not half anymore, the second half was added 15 minutes ago.
Aaronaught
It doesn't work, added files has zero elements.
cw
@cw: Either the added or removed will have zero elements, depending on which one is considered the "final" (which I designated as `first`). Look at the `allChanges` collection.
Aaronaught
thanks that was it. Good Job!
cw