5

What is the best way in C# to get a collection of objects representing the changes between two XML texts, e.g.:

First:

<Customer>
  <Id>1</Id>
  <FirstName>Angie</FirstName>
  <LastName>Jones</LastName>
  <ZipCode>23434</ZipCode>
  <Contracts>
    <Contract>
        <Id>234</Id>
        <Title>Test Contract 1</Title>
    </Contract>
  </Contracts>
</Customer>

Second:

<Customer>
  <Id>1</Id>
  <FirstName>Angie</FirstName>
  <MiddleName>S.</MiddleName>
  <LastName>Jones-Smith</LastName>
  <Contracts>
    <Contract>
        <Id>234</Id>
        <Title>Test Contract 1</Title>
    </Contract>
    <Contract>
        <Id>534</Id>
        <Title>Test Contract 2</Title>
    </Contract>
  </Contracts>
</Customer>

Changes:

Kind:       Node:                  Before     After
--------    ----------             --------   ----------------
Change      Customer/LastName      Jones      Jones-Smith
Addition    Customer/MiddleName               S.
Deletion    Customer/ZipCode
Addition    Customer/Contracts[1]             <Contract>
                                                <Id>534</Id>
                                                <Title>Test Contract 2</Title>
                                              </Contract>

The point is to then pass the changes as a collection of objects onto a GUI which can appropriately display them.

What is the best way to go about this, i.e. structure the class(es) that represents the changes and traverse/examine the XML in order to identify the changes most accurately?

David M
  • 71,481
  • 13
  • 158
  • 186
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047
  • Also need to bear in mind changes in position - had the additional contract been at index [0], then would this need to be identified as an insert at [0], or as a change at [0] plus an addition at [1]. – David M Jan 06 '10 at 16:22

3 Answers3

1

This appears to be a duplicate question for: Xml Comparison in C#

Have a look there, see if it helps.

Quote:

I've got an answer by Martin Honnen in XML and the .NET Framework MSDN Forum. In short he suggests to use XQuery 1.0's deep-equal function and supplies some C# implementations. Seems to work.

Community
  • 1
  • 1
Codesleuth
  • 10,321
  • 8
  • 51
  • 71
0

For this kind of work I have used XMLDiff patch provided by MSFT. It produces a diffgram which you can then represent as a class if you want.

Stan R.
  • 15,757
  • 4
  • 50
  • 58
0

LINQ to XML has a DeepEquals method that I believe you can utilize in this case.

Then perhaps you can use the XSLT/XQuery processor called SAXON to get the differences.

Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
  • 1
    XNode.DeepEquals seems to return a boolean telling me if the two XML texts are equal or not. Is there something similar that gives me a collection of the differences? Something like like "DeepCompare"? – Edward Tanguay Jan 06 '10 at 16:30