0

I am trying to use XMLUnit 1.3 to compare two similar XML files. Basically every thing is same. file1 is a copy of file2.

But in File2 I have changed the order of some values/elements in one node.

file1.xml

<root> 
  <ent> 
   <value> 
     <string>ada,cmb</string>  
   </value>    
  </ent> 
</root>

file2.xml

<root> 
  <ent> 
   <value> 
     <string>cmb,ada</string>  
   </value>    
  </ent> 
</root>

In my case, thease two files must be equal. Is it possible to achieve this with XMLUnit ?

My code

public void testXml() throws ParserConfigurationException, SAXException, IOException {  
    String refXmlPaht = "../test1.xml";
    String testXmlPaht = "../test2.xml";
    Document doc1 = TransformXML.convertXmlToDom(refXmlPaht);
    Document doc2 = TransformXML.convertXmlToDom(testXmlPaht);

    Diff myDiff = new Diff(doc1, doc2);
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreAttributeOrder(true);

    assertXMLEqual("pieces of XML are not similar ", myDiff, true);
    assertTrue("but are they identical? " + myDiff, myDiff.identical());
}

XMLUnit response

junit.framework.AssertionFailedError: but are they identical? 

org.custommonkey.xmlunit.Diff
    [different] Expected text value 'ada,cmb' but was 'cmb,ada' - comparing <string ...>ada,cmb</string> at /root[1]/ent[1]/value[1]/string[1]/text()[1] to <string ...>cmb,ada</string> at /root[1]/ent[1]/value[1]/string[1]/text()[1]...

Thank you for help.

Best regards,

coban

dogbane
  • 266,786
  • 75
  • 396
  • 414
coban
  • 1
  • 1
  • 2
  • 3
    XMLUnit compares the text content, so 'ada, cmb' will never be the same as 'cmb, ada'. Like 'trust' will never be same to 'strut'. Ordering counts here. – kostja Mar 18 '11 at 10:47
  • In order to achieve similarity, you could change your information design - putting two units of information in to one tag/element is not a good idea imho – kostja Mar 18 '11 at 10:48
  • I would like to achieve to ignore ordering. Is this possible? – coban Mar 18 '11 at 10:50
  • 1
    @user432895. nice, so it can be done after all. much better than my wisenheimer approach (+1) – kostja Mar 18 '11 at 12:05

1 Answers1

7

You can create your own DifferenceListener which implements the following method:

int differenceFound(Difference difference);

This method will be called whenever a difference is detected and you can then perform some string checking on the contents of the control and test nodes to see if they mean the same to you. If they are, you can return a value of RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL, so that XMLUnit treats the nodes as being identical.

Take a look at the user guide for more information.

dogbane
  • 266,786
  • 75
  • 396
  • 414