使用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代码: 源xmlSource1 = Input.fromFile(xmlFile1).build(); 源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()为假。
答案 0 :(得分:1)
只需忽略空白(和注释),并检查差异是否包含相似之处(请参见checkForSimilar()
)。
Diff d = DiffBuilder.compare(xmlSource1).withTest(xmlSource2)
.checkForSimilar()
.withNodeMatcher(nodeMatcher)
.ignoreWhitespace()
.ignoreComments()
.build();