Pages

Wednesday, April 29, 2009

Using the XML Diff and Patch Tool in Your Applications

I found an excellent piece of code that compares two XML documents. The difference to the in-built comparer in Linq to XML is that XMLDiff uses comparison options. Hence it is possible to say that the comparison of the XML is to be done ignoring whitespaces, or ignoring the child sort order. This last option is what I was looking for.

At the same time, I prefer to use a common solution or a library than to write the same thing myself, assuming there is one out there.

The project files were created in .Net 1.1 but are easily upgradeable to .Net 3.5.

Usage is extremely easy and straightforward:

[TestMethod]
public void xmldiff_test()
{
XDocument doc1 = this.getDoc1();
XDocument doc2 = this.getDoc1Inverse();

// XMLDiff is using XMLDocument
XmlDocument docx1 = new XmlDocument();
docx1.LoadXml(doc1.ToString());
XmlDocument docx2 = new XmlDocument();
docx2.LoadXml(doc2.ToString());

XmlDiff diff = new XmlDiff();
diff.IgnoreChildOrder = true;
diff.IgnoreXmlDecl = true;
diff.IgnoreWhitespace = true;
bool result = diff.Compare(docx1.DocumentElement, docx2.DocumentElement);

Assert.IsTrue(result);
}


And the two functions create two XML XDocuments with children in different order:



private XDocument getDoc1()
{
XDocument doc = new XDocument(
new XElement("root",
new XElement("child1"),
new XElement("child2")
)
);

return doc;
}

private XDocument getDoc1Inverse()
{
XDocument doc = new XDocument(
new XElement("root",
new XElement("child2"),
new XElement("child1")
)
);

return doc;
}


The link to the text and the download are below:



Using the XML Diff and Patch Tool in Your Applications

No comments: