m0fo
m0fo

Reputation: 2189

Compare 2 XML Files

Is it possible to compare 2 XML files and generate a XML with the delta only?

For example, this is my XML:

<?xml version="1.0" encoding="utf-8"?> 
<Events> 
<Event id="1" date="2012-02-29"> 
<Event id="2" date="2012-02-29"> 
<Event id="3" date="2012-02-29"> 
<Event id="4" date="2012-02-29"> 
<Event id="5" date="2012-02-29"> 
</Events>

And this XML:

<?xml version="1.0" encoding="utf-8"?>
<Events>
<Event id="1" date="2012-02-29">
<Event id="2" date="2012-02-29">
<Event id="3" date="2012-02-29">
<Event id="4" date="2012-02-29">
<Event id="5" date="2012-03-01">
<Event id="6" date="2012-03-01">
<Event id="7" date="2012-03-07">
</Events>

So what I will get after all will be:

<?xml version="1.0" encoding="utf-8"?>
<Events>
<Event id="5" date="2012-03-01">
<Event id="6" date="2012-03-01">
<Event id="7" date="2012-03-07">
</Events>

Because: Event ID 5 changed its date and 6 and 7 are new.

Any idea how can I do with C#?

Upvotes: 0

Views: 2822

Answers (3)

yokuyuki
yokuyuki

Reputation: 98

If you create a DOM tree out of the two XML files, you can traverse both trees to ensure their equivalence. I'm sure there's a DOM library in C# that enables you to do this.

Alternatively, recursively traverse it in XSLT and use the XSLT library in C# to apply the transformation and output the subsequent XML diff.

Upvotes: 1

user1096188
user1096188

Reputation: 1839

This particular example is very easy to get difference for. If real xml files are something like this, you can try to adapt this code:

var doc1 = XDocument.Load(infile1);
var doc2 = XDocument.Load(infile2);
var dict =  doc1.Root.Elements("Event").ToDictionary(el => 
    el.Attribute("id").Value);
doc2.Root.Elements("Event").ToList().ForEach(el => {
    XElement el2;
    if (dict.TryGetValue(el.Attribute("id").Value, out el2) &&
        !el.Attributes().Select(a => new { a.Name, a.Value }).Except(
        el2.Attributes().Select(a => new { a.Name, a.Value })).Any()) 
            el.Remove(); 
});
doc2.Save(outfile);

Upvotes: 1

czuroski
czuroski

Reputation: 4332

You may want to check out the xmldiff patch and gui tool. it allows you to compare 2 xml files - http://msdn.microsoft.com/en-us/library/aa302295.aspx

There is a download link for an exe at the top of this page - http://msdn.microsoft.com/en-us/library/aa302294.aspx

Upvotes: 3

Related Questions