比较XML忽略元素顺序 [英] Compare XML ignoring element order
问题描述
使用XMLUnit 2,如何在不考虑元素顺序的情况下比较两个文档?
With XMLUnit 2 how do you compare two documents without taking the element order into account?
我得到了针对XMLUnit 1的问题,但是显然v2中的新API不再具有上述方法.
I got this question for XMLUnit 1, but apparently the new API in v2 doesn't have the mentioned method anymore.
这是我当前的代码:
Diff diff = DiffBuilder.compare(expected)
.withTest(actual)
.ignoreComments()
.ignoreWhitespace()
.checkForSimilar()
.build();
assertFalse(diff.hasDifferences());
编辑Stefan Bodewigs评论:
Edit to Stefan Bodewigs comment:
这些是我与上面代码段比较的两个字符串:
These are the two strings i compare with above snippet:
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默认情况下按顺序匹配元素.也许这是个坏主意.
One difference that may need to become clearer in the 2.x documentation is the default ElementSelector
- roughly what used to be ElementQualifier
in 1.x. Where 1.x defaults to match elements by name, 2.x defaults to match elements in order. Maybe this is a bad idea.
如果您切换到元素名称的匹配项,则您的Diff应该起作用.
Your Diff should work if you switch to matching on element names.
.withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName))
.withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName))
这篇关于比较XML忽略元素顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!