比较 XML 时如何忽略某些元素?
我有一个像这样的 XML 消息:
<root>
<elementA>something</elementA>
<elementB>something else</elementB>
<elementC>yet another thing</elementC>
</root>
我想将测试中的方法生成的这种类型的消息与预期消息进行比较,但我不关心 elementA
。 因此,我希望上述消息被视为等于:
<root>
<elementA>something different</elementA>
<elementB>something else</elementB>
<elementC>yet another thing</elementC>
</root>
我正在使用最新版本的 XMLUnit 。
我想象答案涉及创建一个自定义的DifferenceListener; 如果有现成的东西可用,我只是不想重新发明轮子。
欢迎提出使用 XMLUnit 以外的库的建议。
I have an XML message like so:
<root>
<elementA>something</elementA>
<elementB>something else</elementB>
<elementC>yet another thing</elementC>
</root>
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>
I'm using the latest version of XMLUnit.
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.
Suggestions that use a library other than XMLUnit are welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我最终实现了一个 DifferenceListener ,它采用节点名称列表(带有命名空间)来忽略文本差异:
I wound up implementing a
DifferenceListener
that takes a list of node names (with namespaces) to ignore textual differences for:自从这个问题得到解答以来,XMLUnit 的情况发生了很大变化。
现在,您可以在使用 DiffBuilder 时轻松忽略节点:
如果您随后调用 documentDiff.hasDifferences() 添加到过滤器的节点将被忽略。
Things have changed a lot for XMLUnit since this question was answered.
You can now easily ignore a node when using a
DiffBuilder
:If you then call
documentDiff.hasDifferences()
nodes added to filter will be ignored.我将使用 XSLT 和 身份转换 来过滤掉我想要的元素忽略并比较结果。
请参阅 XSL:如何复制树,但是删除一些节点? 早些时候就这样。
I would use XSLT and the identity transform to filter out elements I want to ignore, and compare the results.
See XSL: how to copy a tree, but removing some nodes ? earlier on SO.
您现在可以在 XMLUnit 2.6.0 中尝试
${xmlunit.ignore}
(添加依赖项 xmlunit-placeholders)。 示例代码如下。预期 XML:
实际 XML:
请注意,当前 ${xmlunit.ignore} 仅支持文本节点和属性值忽略,从 单元测试。
You can now try
${xmlunit.ignore}
in XMLUnit 2.6.0 (add dependency xmlunit-placeholders). Sample code is as below.Expected XML:
Actual XML:
Do notice that currently the ${xmlunit.ignore} only supports text node and attribute value ignorance, as can be seen from the unit tests.
让我们简单一点,忽略节点,无论您想要忽略多少节点的长度,或者如果您不知道您想要忽略多少节点,请按照以下步骤操作简单步骤
这只是一个 XMLdiff 方法,其中两个 xml 作为字符串
从此链接添加依赖项或 jar https://www.xmlunit.org/
Lets make it simple, to ignore nodes irrespective of length of how many nodes you want to ignore or if you dont know how many number of nodes you want to ignore, follow these simple steps
This is just a XMLdiff method with two xml's as a string
add dependencies or jar from this link https://www.xmlunit.org/