我试图仅使用XMLUnit2部分比较两个xml。我尝试在Xpath下面单独比较元素int
。但我的测试失败了,因为它也在检查boolean
标签。
如何让这个测试通过?
@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());
}
答案 0 :(得分:0)
我不知道这是否是正确的做法。但是无论如何都贴在这里以获得你的评论。通过这种方式,我只能比较XPath评估的XML节点列表。
@Test
public void testXpath() throws Exception {
File controlFile = new File("src/test/resources/myControlXML.xml");
File testFile = new File("src/test/resources/myTest.xml");
Diff myDiff = DiffBuilder.compare(Input.fromDocument(getDocument("src/test/resources/myControlXML.xml", "/struct/int")))
.withTest(Input.fromDocument(getDocument("src/test/resources/myTest.xml", "/struct/int")))
.checkForSimilar().withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName))
.ignoreWhitespace()
.build();
assertFalse("XML similar " + myDiff.toString(),
myDiff.hasDifferences());
}
public Document getDocument(String fileName, String xpathExpression) throws Exception {
File controlFile = new File(fileName);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document controlDoc = dBuilder.parse(controlFile);
controlDoc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xPath.compile(xpathExpression).evaluate(
controlDoc, XPathConstants.NODESET);
Document newXmlDocument = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().newDocument();
Element root = newXmlDocument.createElement("root");
newXmlDocument.appendChild(root);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
Node copyNode = newXmlDocument.importNode(node, true);
root.appendChild(copyNode);
}
return newXmlDocument;
}