Java:使用XMLUnit比较XML [英] Java: Comparing XMLs using XMLUnit

查看:655
本文介绍了Java:使用XMLUnit比较XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用XMLUnit 1.3比较两个相似的XML文件.基本上,每件事都是一样的. file1是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.

但是在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>

在我的情况下,这两个文件必须相等.可以使用XMLUnit实现吗?

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

我的代码

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响应

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]...

感谢您的帮助.

最诚挚的问候,

coban

推荐答案

您可以创建自己的 DifferenceListener ,它实现以下方法:

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

int differenceFound(Difference difference);

只要检测到差异,就会调用此方法,然后您可以对控件和测试节点的内容执行一些字符串检查,以查看它们是否对您有意义.如果是,则可以返回值RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL,以便XMLUnit将节点视为相同.

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.

这篇关于Java:使用XMLUnit比较XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆