比较 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
时轻松忽略节点:
You can now easily ignore a node when using a 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屋!