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

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Convert XLS to XLSX in Java
  • Thread-Safety Pitfalls in XML Processing
  • Loading XML into MongoDB
  • SmartXML: An Alternative to XPath for Complex XML Files

Trending

  • MCP Servers: The Technical Debt That Is Coming
  • System Coexistence: Bridging Legacy and Modern Architecture
  • Optimizing Integration Workflows With Spark Structured Streaming and Cloud Services
  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  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.6K 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

  • How to Convert XLS to XLSX in Java
  • Thread-Safety Pitfalls in XML Processing
  • Loading XML into MongoDB
  • SmartXML: An Alternative to XPath for Complex XML Files

Partner Resources

×

Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: