5

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

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

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

4

3 回答 3

8

我认为这个链接可以帮助你 - http://www.ibm.com/developerworks/java/library/j-cq121906.html#N10158

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

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

<name>和 File2 是一样的,只是顺序不同<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());
}

希望有帮助。

于 2009-11-12T23:18:26.680 回答
3

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 that helps a bit. Read up on XMLUnit here.

于 2014-01-31T07:24:18.600 回答
0
diff =
        DiffBuilder.compare(expected)
          .withTest(toBeVerified)
          .ignoreWhitespace()
          .checkForSimilar()
          .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText, ElementSelectors.byName))
          .build();
于 2021-10-15T08:31:00.320 回答