比较 XML 忽略元素顺序
Compare XML ignoring element order
使用 XMLUnit 2 如何在不考虑元素顺序的情况下比较两个文档?
我得到了 ,但显然 v2 中的新 API 不再具有上述方法。
这是我当前的代码:
Diff diff = DiffBuilder.compare(expected)
.withTest(actual)
.ignoreComments()
.ignoreWhitespace()
.checkForSimilar()
.build();
assertFalse(diff.hasDifferences());
编辑 Stefan Bodewigs 评论:
这些是我与上面的代码片段进行比较的两个字符串:
String expected = "<root><foo>FOO</foo><bar>BAR</bar></root>";
String actual = "<root><bar>BAR</bar><foo>FOO</foo></root>";
报告的差异
Expected element tag name 'foo' but was 'bar' - comparing <foo...> at /root[1]/foo[1] to <bar...> at /root[1]/bar[1] (DIFFERENT)
Expected text value 'FOO' but was 'BAR' - comparing <foo ...>FOO</foo> at /root[1]/foo[1]/text()[1] to <bar ...>BAR</bar> at /root[1]/bar[1]/text()[1] (DIFFERENT)
Expected element tag name 'bar' but was 'foo' - comparing <bar...> at /root[1]/bar[1] to <foo...> at /root[1]/foo[1] (DIFFERENT)
Expected text value 'BAR' but was 'FOO' - comparing <bar ...>BAR</bar> at /root[1]/bar[1]/text()[1] to <foo ...>FOO</foo> at /root[1]/foo[1]/text()[1] (DIFFERENT)
可能需要在 2.x 文档中变得更清楚的一个区别是默认值 ElementSelector
- 大致是 1.x 中的 ElementQualifier
。其中 1.x 默认按名称匹配元素, 2.x 默认按顺序匹配元素。也许这是个坏主意。
如果您切换到匹配元素名称,您的 Diff 应该可以工作。
.withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName))
使用 XMLUnit 2 如何在不考虑元素顺序的情况下比较两个文档?
我得到了
这是我当前的代码:
Diff diff = DiffBuilder.compare(expected)
.withTest(actual)
.ignoreComments()
.ignoreWhitespace()
.checkForSimilar()
.build();
assertFalse(diff.hasDifferences());
编辑 Stefan Bodewigs 评论:
这些是我与上面的代码片段进行比较的两个字符串:
String expected = "<root><foo>FOO</foo><bar>BAR</bar></root>";
String actual = "<root><bar>BAR</bar><foo>FOO</foo></root>";
报告的差异
Expected element tag name 'foo' but was 'bar' - comparing <foo...> at /root[1]/foo[1] to <bar...> at /root[1]/bar[1] (DIFFERENT)
Expected text value 'FOO' but was 'BAR' - comparing <foo ...>FOO</foo> at /root[1]/foo[1]/text()[1] to <bar ...>BAR</bar> at /root[1]/bar[1]/text()[1] (DIFFERENT)
Expected element tag name 'bar' but was 'foo' - comparing <bar...> at /root[1]/bar[1] to <foo...> at /root[1]/foo[1] (DIFFERENT)
Expected text value 'BAR' but was 'FOO' - comparing <bar ...>BAR</bar> at /root[1]/bar[1]/text()[1] to <foo ...>FOO</foo> at /root[1]/foo[1]/text()[1] (DIFFERENT)
可能需要在 2.x 文档中变得更清楚的一个区别是默认值 ElementSelector
- 大致是 1.x 中的 ElementQualifier
。其中 1.x 默认按名称匹配元素, 2.x 默认按顺序匹配元素。也许这是个坏主意。
如果您切换到匹配元素名称,您的 Diff 应该可以工作。
.withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName))