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
Over 2 million developers have joined DZone.
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

  • I Reverse-Engineered 50 API Breaches. The Same Five Mistakes Keep Appearing.
  • The Rise of Microservices Architecture in Scalable Applications
  • A Practical Guide to Temporal Workflow Design Patterns
  • Amazon CodeWhisperer to Q Developer to Kiro: The Rise of Agentic Coding
  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 user avatar
Krishantha Dinesh
·
Jun. 20, 17 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
14.9K Views

Join the DZone community and get the full member experience.

Join For Free

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

The likes didn't load as expected. Please refresh the page and try again.

  • 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