在Java中比较2个XML文档的最佳方式 [英] Best way to compare 2 XML documents in Java

查看:536
本文介绍了在Java中比较2个XML文档的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个应用程序的自动测试,它基本上将自定义消息格式转换为XML消息,并将其发送到另一端。我有一个很好的输入/输出消息对,所以我需要做的是发送输入消息,并监听XML消息出来的另一端。

I'm trying to write an automated test of an application that basically translates a custom message format into an XML message and sends it out the other end. I've got a good set of input/output message pairs so all I need to do is send the input messages in and listen for the XML message to come out the other end.

当比较实际输出和预期输出时,我遇到了一些问题。我的第一个想法只是对预期和实际消息进行字符串比较。这个do不工作很好,因为我们的示例数据不总是格式一致,并且通常有不同的别名用于XML命名空间(有时命名空间根本不使用。)

When it comes time to compare the actual output to the expected output I'm running into some problems. My first thought was just to do string comparisons on the expected and actual messages. This doens't work very well because the example data we have isn't always formatted consistently and there are often times different aliases used for the XML namespace (and sometimes namespaces aren't used at all.)

我知道我可以解析两个字符串,然后遍历每个元素并自己比较,这不会太难做,但我得到的感觉有一个更好的方式或图书馆杠杆。

I know I can parse both strings and then walk through each element and compare them myself and this wouldn't be too difficult to do, but I get the feeling there's a better way or a library I could leverage.

因此,问题是:

给定两个包含有效XML的Java字符串你去确定它们是否在语义上等同?

Given two Java Strings which both contain valid XML how would you go about determining if they are semantically equivalent? Bonus points if you have a way to determine what the differences are.

推荐答案

听起来像是XMLUnit的工作

Sounds like a job for XMLUnit

  • http://www.xmlunit.org/
  • https://github.com/xmlunit

示例:

public class SomeTest extends XMLTestCase {
  @Test
  public void test() {
    String xml1 = ...
    String xml2 = ...

    XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences

    // can also compare xml Documents, InputSources, Readers, Diffs
    assertXMLEquals(xml1, xml2);  // assertXMLEquals comes from XMLTestCase
  }
}

这篇关于在Java中比较2个XML文档的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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