使用xmlunit(2.6.0版(比较两个XML文件会在它们应该被视为相等时产生差异。
XML 1:
<top><a>one</a><b>two</b></top>
XML 2:
<top>
<a>one</a>
<b>two</b>
</top>
Java代码:Source xmlSource1=Input.fromFile(xmlFile1(.build((;Source xmlSource2=Input.fromFile(xmlFile2(.build((;
DefaultNodeMatcher nodeMatcher = new DefaultNodeMatcher(ElementSelectors.byNameAndText);
Diff d = DiffBuilder.compare(xmlSource1)
.withNodeMatcher(nodeMatcher)
.withTest(xmlSource2).build();
Iterable<Difference> diffList = d.getDifferences();
Iterator<Difference> iterator = diffList.iterator();
while(iterator.hasNext()) {
Difference next = iterator.next();
log.info("Difference: " + next);
}
产生此输出:
Difference: Expected child 'top' but was 'null' - comparing <top...> at /top[1] to <NULL> (DIFFERENT)
Difference: Expected child 'null' but was 'top' - comparing <NULL> to <top...> at /top[1] (DIFFERENT)
问题:为什么他们被认为是不同的?如何通过忽略空白差异来进行这种比较?理想情况下,我希望d.hasDifferences((为false。
只需忽略空白(和注释(,并在diff:中不包括相似性(请参见checkForSimilar()
(的地方执行检查
Diff d = DiffBuilder.compare(xmlSource1).withTest(xmlSource2)
.checkForSimilar()
.withNodeMatcher(nodeMatcher)
.ignoreWhitespace()
.ignoreComments()
.build();