Programmatic XML Diff / Merge in C# Programmatic XML Diff / Merge in C# xml xml

Programmatic XML Diff / Merge in C#


After a couple days of messing around, I found a solution that I think works for me. Maybe it could work for other people as well.

The MS XML Diff and Patch tool was a viable option. When you Diff first file against the second file it creates an XML "DiffGram" listing what changes it detected between the two XML files.

To take care of all 3 rules that I listed above, I Diff'd the two files in one direction, then opened the DiffGram file using Linq-to-XML and Removed all the "Add" and "Remove" lines.

XNamespace xd = "http://schemas.microsoft.com/xmltools/2002/xmldiff";var doc = XDocument.Load(_diffGramFile);doc.Root.DescendantsAndSelf(xd + "add").Remove();doc.Root.DescendantsAndSelf(xd + "remove").Remove();

Then I patched up (merged) this edited diffgram against the first file and created a partially merged temporary file. This takes care of Rules 1 and 2.

Next, I Diff'd the partially merged file against the first file used. Then opened the new DiffGram and removed all Change references to "UseExistingValue".

var newdoc = XDocument.Load(_diffGramFile);newdoc.Root.DescendantsAndSelf(xd + "change")      .Where(x => x.Value == "UseExistingValue").Remove();

And merged this edited DiffGram against the partially merged file which takes care of Rule 3. Saving this out to XML then produces the final XML merged according to the rules defined above.

Hopefully this can help out other people.

HINT: After installing the XmlDiffPatch library, the XmlDiffPatch DLL can be found in C:\Windows\assembly\GAC\XmlDiffPatch\1.0.8.28__b03f5f7f11d50a3a\XmlDiffPatch.dll