views:

79

answers:

2

I have frequent need to test that XML files are correct and need a way of testing that 2 XML strings (or documents) are identical, such as:

XMLAssert.assertEquals(String xmlExpected, String xmlActual);

In addition it would be useful to show where the xml documents differed.

This should be restricted to documents with standalone="yes" (i.e. the DTD or schema - if any - is not significant). This means that there are no default values, and attribute types are irrelevant. Adjacent text PCDATA nodes should be normalised (concatenated).

Note that this cannot be done simply by lexical comparison

Assert.assertEquals(xmlExpected, xmlActual);

as there are indefinitely many ways of rendering the same XML infoset. The comparison should take account of namespaces on elements and attributes (but not attribute values - which are not part of the spec).

One way to do this might involve canonicalising both documents. Alternatively an XMLDiff could be used.

I could not find anything so wrote my own a few years ago.

[I also have a particular need to compare floating point values though this must be a hack since the data type of CDATA or PCDATA can only be guessed and is out of immediate scope for the question.]

NOTE: There will probably need to be a specific solution for each language. I am particularly interested in Java and C#

+1  A: 

You can try using the XmlDiffPatch.dll to do that. Go to http://msdn.microsoft.com/en-us/xml/bb190622.aspx, download "XML Diff and Patch", and add the reference to the DLL in your project. I never used it in actual code, but you can try the tool XmlDiff.Exe that comes bundled to see if it fits your needs.

JG
+2  A: 

For Java, you should checkout XMLUnit. And I've just noticed that it comes with a .NET version too! Here's a sample of the Java version:

String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>";
String myTestXML = "<msg><localId>2376</localId></msg>";
assertXMLNotEqual(myControlXML, myTestXML);
Dominic Mitchell
Thanks. This is certainly as comprehensive as I wished and somewhat more powerful than what I wrote. It's a pity I didn't discover this 2 years back
peter.murray.rust