henrik
henrik

Reputation: 1618

Java XMLUnit comparing XML-files with different information ordering

I am trying to validate and check difference between two XML files.

XML-file 1:

<Customer .....>
    <Description description="Foo" name="Foo" language="svSE"/>
    <Description description="Bar" name="Bar" language="enUS"/>
</Customer>

XML-file 2:

<Customer .....>
    <Description description="Bar" name="Bar" language="enUS"/>
    <Description description="Foo" name="Foo" language="svSe"/>
</Customer>

As you can see the description value is in different order in the two files. But they are still both legit XML-files for import.

When trying to compare them in my Unit-test, i get the following Assertion error:

junit.framework.AssertionFailedError: org.custommonkey.xmlunit.Diff [different] Expected attribute value 'Foo' but was 'Bar' - comparing at /message[1]/Customer[1]/Description[1]/@description to at /message[1]/Customer[1]/Description[1]/@description

Here is the XmlUnit java code:

public class FooTest extends AbstractTest {

    ...

    @Test
    public void assertFooBarFile() {

        ...

        XMLUnit.setIgnoreComments(Boolean.TRUE);
        XMLUnit.setIgnoreWhitespace(Boolean.TRUE);
        XMLUnit.setNormalizeWhitespace(Boolean.TRUE);
        XMLUnit.setIgnoreDiffBetweenTextAndCDATA(Boolean.TRUE);
        XMLUnit.setIgnoreAttributeOrder(Boolean.TRUE);
        XMLAssert.assertXMLEqual(doc1, doc2);
    }
}

Any ideas on how I should compare that the both files contain the same information (without caring in which order the information is generated)?

Upvotes: 0

Views: 1295

Answers (2)

henrik
henrik

Reputation: 1618

I solved it by adding:

Diff diff = new Diff(doc1, doc2);
diff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
XMLAssert.assertXMLEqual(diff, Boolean.TRUE);

Upvotes: 1

Pasupathi Rajamanickam
Pasupathi Rajamanickam

Reputation: 2052

You can try this.

public static boolean compareXMLs(String xmlSource, String xmlCompareWith)
        throws Exception {
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreComments(true);
XMLUnit.setIgnoreAttributeOrder(true);

XMLUnit.setNormalizeWhitespace(true);

Diff myDiff = new Diff(xmlSource, xmlCompareWith);
myDiff.similar()
}

Test

String x1 = "<a><a1/><b1/></a>";
String x2 = "<a><b1/><a1/></a>";
assertTrue(compareXMLs(x1, x2));

Upvotes: 1

Related Questions