Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Comparing Unsorted (Unordered) Whitespace in Different XML Files

DZone's Guide to

Comparing Unsorted (Unordered) Whitespace in Different XML Files

Comparing XML files can be a nightmare, particularly where whitespace is concerned. Fortunately, there's a free, open tool—XMLUnit—that can help.

· Java Zone
Free Resource

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

Many developers struggle to compare XML files. There are a number of reasons for that, including:

  • Whitespace differences

  • Unordered

  • Comment differences

CData differences can cause different results. 

Most of the time, developers try to convert XML into Strings to do the comparison. If this is for unit testing, performance may not be an issue. But again, if the format is different or whitespace/comments are different, then the test will fail — and that is a false failure.

XMLUnit is the solution for this. The following example will demonstrate how you can compare unsorted XML files even with whitespaces.

Maven dependencies:

<dependencies>
    <dependency>
        <groupId>xmlunit</groupId>
        <artifactId>xmlunit</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>


Java class:

package com.krishantha.sample;

import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.Iterator;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
/**
 * Created by krishantha on 12/2/15.
 */
public class XmlComparator {
    public static void main(String[] args) throws IOException, SAXException {
        xmlComparator("src/original.xml", "src/response.xml");
    }

    private static void xmlComparator(String expectedXmlFilePath, String currentXmlFilePath) throws SAXException, IOException {
        //ignore while space differances
        XMLUnit.setIgnoreWhitespace(true);
        //ignore attribute order
        XMLUnit.setIgnoreAttributeOrder(true);
        //ignore comment differances
        XMLUnit.setIgnoreComments(true);
        //ignore differance on CData and text
        XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);

        InputSource expected = new InputSource(expectedXmlFilePath);
        InputSource current = new InputSource(currentXmlFilePath);

        DetailedDiff detailedDiff = new DetailedDiff(new Diff(expected, current));

        //ignore the sorting mismatch issues
        detailedDiff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());

        //this will print even if order mismatch elements are there. if you want to skip this use assertor
        Iterator i = detailedDiff.getAllDifferences().iterator();
        while (i.hasNext()) {
            System.out.println(i.next().toString());
        }
        System.out.println("================== if soarting issues are ignored =============================");
        //this can use ignore soarting issues and assert
        assertXMLEqual("XML files are mismatch", detailedDiff, true);
    }
}


Target xml file (expected)

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    <!--
     this is one comment
    -->
    <url>
        <loc>http://www.krishantha.net/</loc>
    </url>
    <url>
        <loc>http://www.krishantha.net/tag/multi-root-xml/</loc>
    </url>
    <url>
        <loc>http://www.krishantha.net/tag/oauth/</loc>
    </url>
    <url>
        <loc>http://www.krishantha.net/tag/payload/</loc>
    </url>
    <url>
        <loc>
            http://www.krishantha.net/log-incoming-request-of-soap-ui-mock-service/
        </loc>
    </url>
    <url>
        <loc>
            http://www.krishantha.net/data-masking-with-wso2-esb-and-xslt/
        </loc>
    </url>
</urlset>


Source XML file:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    <!--
     this is other comment
    -->
    <url>
        <loc>
            http://www.krishantha.net/log-incoming-request-of-soap-ui-mock-service/
        </loc>
    </url>





    <url>
        <loc>
            http://www.krishantha.net/data-masking-with-wso2-esb-and-xslt/
        </loc>
    </url>
    <url>
        <loc>http://www.krishantha.net/</loc>
    </url>
    <url>
        <loc>http://www.krishantha.net/tag/multi-root-xml/</loc>
    </url>
    <url>
        <loc>http://www.krishantha.net/tag/oauth/</loc>
    </url>
    <url>
        <loc>http://www.krishantha.net/tag/payload/</loc>
    </url>
</urlset>


When you execute, you'll see there are no failures. But if you made any changes (content) to either XML file, you will see a fail on assert.

If you'd like to play around more with this, a sample project can be downloaded here

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
java ,xml ,xmlunit ,white space ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}