如何比较XMLUnit中的两个相似的XML文件

时间:2009-11-12 22:57:25

标签: xmlunit

我想使用XMLUnit来比较两个相似的XML文件。

基本上每件事情都是一样的,File1File2的副本,但在File2我改变了一个节点中某些元素的顺序。

我正在尝试运行测试,比较这些文件并返回类似的结果,而不是将这些文件视为不同

2 个答案:

答案 0 :(得分:8)

我认为此链接可以为您提供帮助 - http://www.ibm.com/developerworks/java/library/j-cq121906.html#N10158

基本上,如果你的File1就像 -

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

File2相同,但只是按<name><id> -

的顺序不同
<account>
 <name>acme</name>
 <id>3A-00</id>
</account> 

然后你可以写下面的测试,它将比较这些并返回类似的。

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());
}

希望有所帮助。

答案 1 :(得分:3)

这应该这样做:

    // 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());

希望有所帮助。阅读XMLUnit here