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

查看:27
本文介绍了在 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.

当需要将实际输出与预期输出进行比较时,我遇到了一些问题.我的第一个想法是对预期和实际消息进行字符串比较.这不太好用,因为我们拥有的示例数据的格式并不总是一致,而且 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.

所以,归结起来,问题是:

So, boiled down, the question is:

给定两个都包含有效 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

示例:

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
    assertXMLEqual(xml1, xml2);  // assertXMLEquals comes from XMLTestCase
  }
}

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

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