How to compare two similar XML files in XMLUnit

I want to use XMLUnit to compare two similar XML files.

In principle, everything is the same, File1 is a copy of File2 , but in File2 I changed the order of some elements in one node.

I try to run a test where it compares these files and returns the result of the similar ones and does not treat these files as different.

+4
source share
2 answers

I think this link may help you - http://www.ibm.com/developerworks/java/library/j-cq121906.html#N10158

Basically, if your File1 is like -

 <account> <id>3A-00</id> <name>acme</name> </account> 

And File2 is the same, but only different from <name> and <id> -

 <account> <name>acme</name> <id>3A-00</id> </account> 

You can then write a test, as shown below, that will compare them and return similar ones.

 public void testIdenticalAndSimilar() throws Exception { String controlXML = "<account><id>3A-00</id><name>acme</name></account>"; String testXML = "<account><name>acme</name><id>3A-00</id></account>"; Diff diff = new Diff(controlXML, testXML); assertTrue(diff.similar()); assertFalse(diff.identical()); } 

Hope this helps.

+7
source

This should do it:

  // Assuming file1 and file2 are not deeply nested XML files DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc1 = docBuilder.parse(file1); Document doc2 = docBuilder.parse(file2); // SOLUTION 1: Are the files "similar"? Diff diff = new Diff(doc1, doc2); System.out.println("Similar (true/false): " + diff.similar()); // SOLUTION 2: Should you want detailed differences (especially useful for deeply nested files) Diff diff = new Diff(doc1, doc2); diff.overrideElementQualifier(new RecursiveElementNameAndTextQualifier()); DetailedDiff detailedDiff = new DetailedDiff(diff); System.out.println("Detailed differences: " + detailedDiff.getAllDifferences().toString()); 

Hope this helps. Read on XMLUnit here .

+3
source

All Articles