DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The Hidden Engineering Cost of XML in Enterprise Development Workflows
  • How to Convert XLS to XLSX in Java
  • Thread-Safety Pitfalls in XML Processing
  • Loading XML into MongoDB

Trending

  • Why Role-Based Access Control Fails for AI Agents — and How to Fix It With Memory Lineage Engines
  • Designing Frontend Applications for Failure, Not Just Success
  • The Permission Was Valid. The Action Was Not Authorized.
  • Moving 900+ GB of Prometheus Without a Cutover Weekend

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Comparing Unsorted (Unordered) Whitespace in Different XML Files

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.

By 
Krishantha Dinesh
·
Jun. 20, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
15.0K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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. 

XML

Opinions expressed by DZone contributors are their own.

Related

  • The Hidden Engineering Cost of XML in Enterprise Development Workflows
  • How to Convert XLS to XLSX in Java
  • Thread-Safety Pitfalls in XML Processing
  • Loading XML into MongoDB

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook