开发者

Java: Comparing XMLs using XMLUnit

开发者 https://www.devze.com 2023-02-18 18:20 出处:网络
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.

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 = ".开发者_如何学JAVA./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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号