我想比較兩個XML只部分使用XMLUnit2。我在Xpath下面嘗試單獨比較元素int
。但是我的測試失敗了,因爲它正在檢查boolean
標記。如何使用XMLUnit2通過XPATH比較xmls?
我該如何通過此測試?
@Test
public void diff_through_xPath(){
String myControlXML = "<struct><boolean>false</boolean><int>3</int></struct>";
String myTestXML = "<struct><boolean>true</boolean><int>3</int></struct>";
ElementSelector childSelector = selectorForElementNamed("int", byXPath("//int", byName));
Diff myDiffSimilar = DiffBuilder.compare(myControlXML).withTest(myTestXML)
.withNodeMatcher(new DefaultNodeMatcher(childSelector, byName))
.checkForSimilar()
.ignoreWhitespace()
.build();
assertFalse("XML similar " + myDiffSimilar.toString(),
myDiffSimilar.hasDifferences());
}
編輯: 隨着NodeFilter,我刪除了不必要的節點從對比。但是有沒有辦法給Xpath,只比較XPath評估的節點。
@Test
public void diff_through_xPath() {
String myControlXML = "<struct><boolean>false</boolean><int>3</int></struct>";
String myTestXML = "<struct><boolean>true</boolean><int>3</int></struct>";
Diff myDiffSimilar = DiffBuilder.compare(myControlXML).withTest(myTestXML)
.withNodeFilter(new Predicate<Node>() {
public boolean test(Node node) {
return !node.getNodeName().equals("boolean"); //ignores all child nodes from of 'a'.
}
})
//.checkForSimilar()
.ignoreWhitespace()
.build();
assertFalse("XML similar " + myDiffSimilar.toString(),
myDiffSimilar.hasDifferences());
}
我不知道我明白你想要比較什麼。你想比較所有'struct'還是僅僅'int's? 'NodeMatcher'用於決定一組兄弟節點中的哪些節點進行比較,它根本不會影響哪些節點有資格進行比較。你會使用'NodeFilter'來去掉那些你不想要的東西。 –
我想比較兩個xml中的'int'標記。我不在乎布爾標籤是否匹配。 – Manoj
由於我編輯過,我可以使用Nodefilter刪除不需要的節點。有沒有辦法使用Xpath和比較? – Manoj