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

末鹿安然 提交于 2019-12-02 04:28:42

问题


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:


RecursiveElementNameAndTextQualifier will yield the same result as the default ElementNameQualifier - b and c are out of order but other than that the documents are identical.

Elements that are out of order constitute a recoverable difference, so Diff and DetailedDiff will say the documents are "similar" but not "identical". So either you ignore recoverable differences or you must override the DifferenceListener rather than the ElementQualifier to downgrade a difference of type CHILD_NODELIST_SEQUENCE_ID from RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR (the default) to RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL. Something like

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

which accepts the default but downgrades just the out-of-order differences.



来源:https://stackoverflow.com/questions/31057788/how-do-i-ignore-order-of-identical-elements-with-xmlunits-detaileddifference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!