将 XML 个相等的文件(空格除外)与 xmlunit 进行比较会产生差异
Comparing XML equal files (except for whitespace) with xmlunit produces difference
使用 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() 为假。
只需忽略空格(和注释)并执行检查差异中未包含相似之处(参见 checkForSimilar()
)的地方:
Diff d = DiffBuilder.compare(xmlSource1).withTest(xmlSource2)
.checkForSimilar()
.withNodeMatcher(nodeMatcher)
.ignoreWhitespace()
.ignoreComments()
.build();
使用 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() 为假。
只需忽略空格(和注释)并执行检查差异中未包含相似之处(参见 checkForSimilar()
)的地方:
Diff d = DiffBuilder.compare(xmlSource1).withTest(xmlSource2)
.checkForSimilar()
.withNodeMatcher(nodeMatcher)
.ignoreWhitespace()
.ignoreComments()
.build();