比较Groovy / Java中的两个XML字符串/文件 [英] Comparing two XML strings/files in Groovy/Java

查看:414
本文介绍了比较Groovy / Java中的两个XML字符串/文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写单元测试来检查一些XML生成器。



现在我遇到了预期结果和实际结果之间语法差异的问题,

预期结果:

 < parent>< child attr =test attribute> text here< / child>< / parent> 

实际结果:

 < parent> 
< child attr =test attribute>
text here
< / child>
< / parent>

我尝试使用XmlUtil.serialize()规范化xml,但是这似乎保留了空白,离开语法上的差异。



如何获得规范化/规范的xml字符串形式,以使我的测试更加强大?


$ b $

解决方案

我正在编写Grails应用程序,所以我对Groovy或Java中的任何解决方案都很好。您可以使用Groovy XMLUnit 实用程序:

  XMLUnit.setIgnoreWhitespace(true)
XMLUnit.setIgnoreComments(true)
XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true)
XMLUnit.setNormalizeWhitespace(true)

XMLUnit.compareXML(expectedXml,actualXml)

比较XML文件,同时忽略句法差异。


I'm writing unit tests for checking some XML builder.

Now I'm running into the problem of syntactical differences between the expected result and the actual result, despite their identical semantics.

Example:

Expected result:

<parent><child attr="test attribute">text here</child></parent>

Actual result:

<parent>
  <child attr="test attribute">
    text here
  </child>
</parent>

I tried normalizing the xml using XmlUtil.serialize(), however this seems to keep the whitespaces, leaving syntactical differences.

How can I get the normalized/canonical form of xml strings in order to make my tests more robust?

I'm writing a Grails application, so I'm fine with any solution in Groovy or Java.

解决方案

You can use the Groovy XMLUnit utility like this:

XMLUnit.setIgnoreWhitespace(true)
XMLUnit.setIgnoreComments(true)
XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true)
XMLUnit.setNormalizeWhitespace(true)

XMLUnit.compareXML(expectedXml, actualXml)

To compare XML files while ignoring the syntactical differences.

这篇关于比较Groovy / Java中的两个XML字符串/文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆