Search This Blog

Tuesday, March 6, 2007

Comparing two XML documents

When writing unit tests involving XML you often want to compare two XML documents. This can easily be done using a simple String compare as in:

expectedXML.equals(responseXML);

Where ‘expectedXML’ is the XML we expect to get back and ‘responseXML’ is the actual XML that is given as a response.

The problem with this approach is that it not only compares the actual XML but also any unimportant whitespace, tabs etc. This is not the desired behavior because it breaks our test when, for example, whitespaces are added in de reponseXML.

One solution to this problem is to use a handy utility class named DocumentComparator, which is part of the JIBX distribution. The javadoc of the DocumentComparator says the following:

XML document comparator. This uses XMLPull parsers to read a pair of documents in parallel, comparing the streams of components seen from the two documents. The comparison ignores differences in whitespace separating elements, but treats whitespace as significant within elements with only character data content.

This is exactly the functionality we need. With this class we can write the following code to compare two XML documents:

ByteArrayOutputStream out = new ByteArrayOutputStream();
DocumentComparator comp = new DocumentComparator(new PrintStream(out));
boolean result =comp.compare(new StringReader(responseXml), new StringReader(expectedXml));
assertEquals(out.toString(), true, result);

The DocumentComparator class uses the PrintStream to report any differences found when comparing the two documents.