2014-07-07 66 views
0

比較我有2個XML進行比較:XMLUnit測試 - 兩個個XML具有不同的節點

File1.xml

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

File2.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] 

我需要表示輸出,以便它只告訴我以下差異: 節點CandidateID在File1.xml中缺失,並且節點CandidateName的數據差異。我不需要額外的細節。有沒有辦法來調整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("***********************"); 
    } 

回答

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之前。

相關問題