正如其他人所提到的,XMLUnit 将内部的文本(由一个新行组成)<element1>
视为一个子节点。<element1
另一个 XML 中的>没有任何子节点(甚至没有空文本)。
如果您想忽略这种差异,则必须编写自定义DifferenceListener
:
Diff diff = new Diff(doc1, doc2);
diff.overrideDifferenceListener(new DifferenceListener() {
...
@Override
public int differenceFound(Difference difference) {
if(difference.getId() == DifferenceConstants.HAS_CHILD_NODES_ID) {
Node controlNode = difference.getControlNodeDetail().getNode();
Node testNode = difference.getTestNodeDetail().getNode();
if(controlNode.getChildNodes().getLength() == 0) {
Node childNode = testNode.getChildNodes().item(0);
// note the trim method call
if(childNode.getNodeType() == Node.TEXT_NODE
&& childNode.getTextContent().trim().isEmpty()) {
return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
}
} else { // we're sure the other node has children in the else part
Node childNode = controlNode.getChildNodes().item(0);
if(childNode.getNodeType() == Node.TEXT_NODE
&& childNode.getTextContent().trim().isEmpty()) {
return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
}
}
}
return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
}
});