0

我有 2 个要比较的 XML:

文件1.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<member>
    <SchoolID>1021</SchoolID>
    <CandidateType>First Year</CandidateType>
    <CandidateName>John</CandidateName>
</member>

文件2.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<member>
    <CandidateID>3147</CandidateID>
    <SchoolID>1021</SchoolID>
    <CandidateType>Second Year</CandidateType>
    <CandidateName>Peter</CandidateName>
</member>

我正在使用 xmlunit 进行比较,但是我得到的输出如下:

Similar? false
Identical? false
***********************
Expected number of child nodes '2' but was '3' - comparing <member...> at /member[1] to <member...> at /member[1]
***********************
***********************
Expected sequence of child nodes '0' but was '1' - comparing <SchoolID...> at /member[1]/SchoolID[1] to <SchoolID...> at /member[1]/SchoolID[1]
***********************
***********************
Expected text value 'John' but was 'Peter' - comparing <CandidateName ...>John</CandidateName> at /member[1]/CandidateName[1]/text()[1] to <CandidateName ...>Peter</CandidateName> at /member[1]/CandidateName[1]/text()[1]
***********************
***********************
Expected sequence of child nodes '1' but was '2' - comparing <CandidateName...> at /member[1]/CandidateName[1] to <CandidateName...> at /member[1]/CandidateName[1]
***********************
***********************
Expected presence of child node 'null' but was 'CandidateID' - comparing  at null to <CandidateID...> at /member[1]/CandidateID[1]

我需要表示输出,以便它只告诉我以下差异:File1.xml 中缺少节点 CandidateID 以及节点候选名称的数据差异。我不需要额外的细节。有没有办法调整 detDiff.getAllDifferences() 的输出。

代码快照如下所示:

try {
// fr1 and fr2 are my two xml files.
    Diff diff = new Diff(fr1, fr2); 
    System.out.println("Similar? " + diff.similar());
    System.out.println("Identical? " + diff.identical());

    DetailedDiff detDiff = new DetailedDiff(diff);
    List differences = detDiff.getAllDifferences();
    for (Object object : differences) {
        Difference difference = (Difference)object;
        System.out.println("***********************");
        System.out.println(difference);
        System.out.println("***********************");
    }
4

1 回答 1

2

根据您的需要,您可以在比较之后过滤差异或覆盖DifferenceListener以忽略您不感兴趣的差异。

对于过滤,您似乎只需查看isRecoverable并去除所有可恢复的差异。

一个习惯DifferenceListener就像

    detDiff.overrideDifferenceListener(new DifferenceListener() {
            @Override
            public int differenceFound(Difference diff) {
                if (diff.getId() == DifferenceConstants.CHILD_NODELIST_SEQUENCE_ID
                    || diff.getId() == DifferenceConstants.CHILD_NODELIST_LENGTH_ID) {
                    return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
                }
                return RETURN_ACCEPT_DIFFERENCE;
            }
            @Override
            public void skippedComparison(Node arg0, Node arg1) { }
        });

在你打电话之前getAllDifferences

于 2015-02-03T19:34:43.693 回答