2009-12-05 80 views
1

如何使用XMLUnit比較2個不同文件中的2個或更多節點(同名)?如何使用XMLUnit比較文件的某些部分?

我有一個看起來像這樣2個XML文件:

<SearchResults> 
    <result type="header"> ...ignore this.... </result> 
    <result type="secondheader">...ignore this....</result> 
    <result>....data1....</result> 
    <result>....data2....</result> 
    <result>....data3....</result> 
    <result type="footer">...ignore this....</result> 
</SearchResults> 

這裏是我的方法,我用到目前爲止比較。問題是我不想比較帶有結果標籤的xml部分和其上的任何類型的屬性標誌。我怎樣才能做到這一點?

public void compareXMLEqualityToLastTest() throws Exception { 
    System.out.println("Checking differences."); 
    File firstFile = new File("C:\\Eclipse\\workspace\\Tests\\log\\" + 
       "Test_2.xml"); 
    String file1sub = readXMLFromFile(firstFile); 
    File secondFile= new File("C:\\Eclipse\\workspace\\Tests\\log\\" + 
       "Test_1.xml"); 
    String file2sub = readXMLFromFile(secondFile); 
    assertXMLNotEqual("files are equal", file1sub, file2sub); 
    assertXMLEqual("files are not equal", file1sub, file2sub); 
} 

我發現了一個模糊的建議到XMLUnit測試說明書第5頁上使用ElementQualifier,但我不明白它。我不知道如何告訴它要比較哪個節點。

Diff myDiff = new Diff(file1sub, file2sub); 
     myDiff.overrideElementQualifier(new ElementNameAndTextQualifier()); 
     assertXMLEqual("But they are equal when an ElementQualifier controls " + 
    "which test element is compared with each control element", myDiff, true); 

我應該遵循該路線並將此類添加到我的項目中嗎?

org.apache.wink.test.diff.DiffWithAttributeQualifier 

的念頭閃過我的腦海裏把節點分成的NodeList,然後用org.custommonkey.xmlunit.compareNodeList但感覺就像是一個黑客。有沒有比這更好的方法?

回答

3

使用XPath測試會不會更容易?我想象這樣的工作

//select all elements which don't have a type attribute 
String xpath = "//result[not(@type)]"; 
assertXpathsEqual(xpath, file1sub, xpath, file1sub2) 
+0

看起來像答案,只要assertXpathsEqual能夠得到一個NodeList而不只是一個節點。我會試試看。非常感謝這個想法。 – djangofan 2009-12-05 04:41:17

+0

謝謝!這工作:String xpath =「// result [not(@type)]」; assertXpathsEqual(xpath,file1sub,xpath,file2sub); – djangofan 2009-12-05 04:56:54