比较XML时如何忽略某些元素? [英] How do I ignore certain elements when comparing XML?
问题描述
我有这样的XML消息:
I have an XML message like so:
<root>
<elementA>something</elementA>
<elementB>something else</elementB>
<elementC>yet another thing</elementC>
</root>
我想将被测方法生成的此类消息与预期消息进行比较,但是我不关心 elementA
。所以,我希望上述消息被视为等于:
I want to compare a message of this type produced by a method under test to an expected message, but I don't care about elementA
. So, I'd like the above message to be considered equal to:
<root>
<elementA>something different</elementA>
<elementB>something else</elementB>
<elementC>yet another thing</elementC>
</root>
我正在使用最新版本的 XMLUnit 。
I'm using the latest version of XMLUnit.
我想这个答案涉及创建自定义 DifferenceListener
;如果有可以在那里使用的话,我只是不想重新发明轮子。
I'm imagining that the answer involves creating a custom DifferenceListener
; I just don't want to reinvent the wheel if there's something ready to use out there.
欢迎使用XMLUnit以外的库的建议。
Suggestions that use a library other than XMLUnit are welcome.
推荐答案
XMLUnit ,因为这个问题已得到解答。
Things have changed a lot for XMLUnit since this question was answered.
现在,您可以在使用 DiffBuilder
:
final Diff documentDiff = DiffBuilder
.compare(expectedSource)
.withTest(actualSource)
.withNodeFilter(node -> !node.getNodeName().equals(someName))
.build();
如果你再调用 documentDiff.hasDifferences()
添加到过滤器的节点将被忽略。
If you then call documentDiff.hasDifferences()
nodes added to filter will be ignored.
这篇关于比较XML时如何忽略某些元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!