How do I ignore order of identical elements with XMLUnit's DetailedDifference?

时间:2015-06-25 18:15:07

标签: java xmlunit

I want to compare two xml files using XMLUnit. I would like the DetailedDiff to not report identical tags in different orders as differences. For example, if I created a DetailedDiff with these two snippets:

 <a><b/><c/></a>

and

<a><c/><b/></a>

The DetailedDiff will create two Differences since the b and c tags are out of order. I have tried overriding element qualifiers but it doesn't result in any changes. Am I doing something wrong or is this impossible to do with XMLUnit? For reference here's the code I'm using to compare two xml files (not including overrideElementQualifier calls).

public List<Difference> getDifferenceList(Reader file1, Reader file2) {
    Diff d = new Diff(file1, file2); //I'm passing the args as FileReaders
    d.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
    detailedDiff = new DetailedDiff(d);
    List<Difference> allDifferences = detailedDiff.getAllDifferences();
    return allDifferences;
}

1 个答案:

答案 0 :(得分:5)

RecursiveElementNameAndTextQualifier将产生与默认ElementNameQualifier相同的结果 - b和c无序,但除了文档相同之外。

无序的元素构成了可恢复的差异,因此DiffDetailedDiff会说文档类似于&#34;类似的&#34;但不是&#34;相同&#34;。因此,要么忽略可恢复的差异,要么必须覆盖DifferenceListener而不是ElementQualifierCHILD_NODELIST_SEQUENCE_ID的差异从RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR(默认值)降级为RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL }。像

这样的东西
public int differenceFound(Difference difference) {
    return difference.getId() == DifferenceConstants.CHILD_NODELIST_SEQUENCE_ID
        ? RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL
        : RETURN_ACCEPT_DIFFERENCE;
}

接受默认值,但仅降低无序差异。

相关问题