Java 比较两个XML文档失败,因为文档来自两个源

Java 比较两个XML文档失败,因为文档来自两个源,java,xml,Java,Xml,我已使用以下代码将字符串转换为XML文档: String xmlStr = "<msg><uuid>12345</uuid></msg>" DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); Document d

我已使用以下代码将字符串转换为XML文档:

String xmlStr = "<msg><uuid>12345</uuid></msg>"
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
  builder = factory.newDocumentBuilder();
  Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
  return doc;
} catch (Exception e) {
  throw new RuntimeException(e);
}
最后,我比较了两份文件:

Document actualDoc = XmlUtils.convertStringToDocument(xmlString);
Diff myDiff = new Diff(expectedDoc, actualDoc);
assert (myDiff.similar());
使用如下格式的XML文件(xmlforjunitest.XML)通过此测试:

<msg><uuid>12345</uuid></msg>
12345
它在这方面失败了:

<msg>
   <uuid>12345</uuid>
</msg>

12345

请您说明发生此故障的原因,以及解决方案是什么?

断言失败,因为一个文档包含空格,而另一个文档不包含空格。我认为您需要查看
XmlUnit
中的
normalizeWhitespace
标志(假设您正在使用该标志)。

您忘了问一个问题,我建议您阅读
<msg>
   <uuid>12345</uuid>
</msg>