XMLUnit - Compare two XML ignoring the child order

user320587 picture user320587 · Oct 15, 2010 · Viewed 7.2k times · Source

I am trying to see if I could use XMLUnit to compare the following two different XML. I used the Diff class to compare the following two XML and checking for similar returns false.

XML One
<Required>
   <Question desc="Are you single?">
      <Answers>
        <Answer value="Yes"/>
        <Answer value="No"/>
      </Answers>
   </Question>
</Required>

XML Two
<Required>
   <Question desc="Are you single?">
      <Answers>
        <Answer value="No"/> ''Order is reversed in XML two
        <Answer value="Yes"/>
      </Answers>
   </Question>
</Required>

Here is my JAVA code:

Diff xmlDiff;
try {
    xmlDiff = new Diff(xmlOne, xmlTwo);
    xmlDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
} catch (Exception e) { }
boolean isEqual = xmlDiff.similar()

Answer

Buhb picture Buhb · Oct 15, 2010

xmlDiff.similar should do the trick, but I've experienced that this doesn't always work. My workaround was to sort the elements before comparison.

Note that it is often a good idea to build into you application to have well defined ordering in your output since this makes automatic testing that much easier.