问题描述
我在下面有两个不同的 XML 文档,请注意它们具有相同的基本结构(架构)。
源 XML
<root>
<name>String</name>
<description>String</description>
</root>
测试 XML
<root>
<name>Test</name>
<description></description> <!-- it is an empty node -->
</root>
我构建了这个片段函数来比较这两个 XML 文档。
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.IgnoreTextAndAttributeValuesDifferenceListener;
import org.custommonkey.xmlunit.XMLUnit;
public static void main(String args[]) throws FileNotFoundException,SAXException,IOException,ParserConfigurationException,XPathExpressionException {
String strSource = "<root><name>String</name><description>String</description></root>";
String strTest = "<root><name>Test</name><description></description></root>";
Document docSource = stringToXMLDocument(strSource);
Document docTest = stringToXMLDocument(strTest);
boolean result = isMatched(docSource,docTest);
if(result){
System.out.println("Matched!");
}else{
System.out.println("Un-matched!");
}
}
public static boolean isMatched(Document xmlSource,Document xmlCompareWith) {
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreComments(true);
XMLUnit.setIgnoreAttributeOrder(true);
XMLUnit.setnormalizeWhitespace(true);
XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);
Diff myDiff = new Diff(xmlSource,xmlCompareWith);
myDiff.overrideDifferenceListener(new IgnoreTextAndAttributeValuesDifferenceListener());
return myDiff.similar();
}
public static Document stringToXMLDocument(String str) throws ParserConfigurationException,IOException{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new InputSource(new StringReader(str)));
return document;
}
这里是Maven依赖
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.6</version>
</dependency>
我期望这两个 XML 文档是相同的,但函数总是返回 false。在比较两个 XML 结构时,有什么方法可以忽略节点文本值。如您所见,我已经使用了 IgnoreTextAndAttributeValuesDifferenceListener,但问题仍然存在。
解决方法
您可能需要提供自己的 DifferenceListener
来委托给 IgnoreTextAndAttributeValuesDifferenceListener
并另外处理 HAS_CHILDNODES
和 CHILD_NODELIST_LENGTH
类型的差异。
正如@scott-kurz 在 cmments 中指出的那样,可能根本没有任何 XML Text
节点,而不是一个空节点,这取决于您的 XML 解析器及其配置。