DEV Community

Cover image for Get Diff and Patch Html
Antoine
Antoine

Posted on

Get Diff and Patch Html

Photo by Markus Spiske on Diff.Match.Patch based on Google library.

Diff

Diff are made of:

  • text (part of the text related)
  • operation to be applied (delete / insert / equal)

It's easy to get diff:

    string a = "<SPAN TITLE=\"i=0\">a&para;<BR></SPAN><DEL STYLE=\"background:#FFE6E6;\" TITLE=\"i=2\">&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE=\"background:#E6FFE6;\" TITLE=\"i=2\">c&amp;d</INS>";
    string b = "<SPAN TITLE=\"i=0\">testa&para;<BR></SPAN><DEL STYLE=\":#FFE6E6;\" TITLE=\"i=2\">&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE=\"background:#E6FFE6;\" TITLE=\"i=2\">c&amp;d</INS>";

var diffs = DiffMatchPatchModule.Default.DiffMain(a, b);

Enter fullscreen mode Exit fullscreen mode

Please note that diffs will contains a lot of Equal diff !
Result: Result

Patch

It's simple too to get patch from multiple texts!

    string a = "<SPAN TITLE=\"i=0\">a&para;<BR></SPAN><DEL STYLE=\"background:#FFE6E6;\" TITLE=\"i=2\">&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE=\"background:#E6FFE6;\" TITLE=\"i=2\">c&amp;d</INS>";
    string b = "<SPAN TITLE=\"i=0\">testa&para;<BR></SPAN><DEL STYLE=\":#FFE6E6;\" TITLE=\"i=2\">&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE=\"background:#E6FFE6;\" TITLE=\"i=2\">c&amp;d</INS>";
    string c = "<SPAN TITLE=\"i=0\">a&para;<BR></SPAN><DEL STYLE=\"background:#FFE6E6;\" TITLE=\"i=2\">mon tittre en Or&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE=\"background:#E6FFE6;\" TITLE=\"i=2\">c&amp;d</INS>";

    var firstPatch = DiffMatchPatchModule.Default.PatchMake(a, b);
    var secondPatch = DiffMatchPatchModule.Default.PatchMake(a, c);
    DiffMatchPatchModule.Default.PatchApply(secondPatch, DiffMatchPatchModule.Default.PatchApply(firstPatch, a)[0].ToString());

Enter fullscreen mode Exit fullscreen mode

Ouptut:

<SPAN TITLE="i=0">testa&para;<BR></SPAN><DEL STYLE=":#FFE6E6;" TITLE="i=2">mon tittre en Or&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE="background:#E6FFE6;" TITLE="i=2">c&amp;d</INS>
Enter fullscreen mode Exit fullscreen mode

Please note that DiffMatchPatchModule.Default.PatchApply(firstPatch, a) outputs object[] !

Hope that helps !

Top comments (0)