I have two different XML documents below and please note that they are having the same basic structure (schema).
Source XML
<root>
<name>String</name>
<description>String</description>
</root>
Test XML
<root>
<name>Test</name>
<description></description> <!-- it is an empty node -->
</root>
And I build this snippet function to compare those two XML documents.
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.IgnoreTextAndAttributeVal uesDifferenceListener;
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, SAXException, IOException{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new InputSource(new StringReader(str)));
return document;
}
And here is the Maven dependency
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.6</version>
</dependency>
I am expecting those two XML documents are the same, but the function always returns false. Are there any ways that I can ignore the node text value when comparing two XML structures? As you can see, I already used IgnoreTextAndAttributeValuesDifferenceListener, but I still got the problem.