Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two xml files using JAVA

Tags:

java

xml

I have to xml files say abc.xml & 123.xml which are almost similar, i mean has the same content, but the second one i.e, 123.xml has more content than the earlier one. I want to read both the files using Java, and compare whether the content present in abc.xml for each tag is same as that in 123.xml, something like object comparison. Please suggest me how to read the xml file using java and start comparing.

Thanks.

like image 236
Sangram Anand Avatar asked Apr 25 '12 07:04

Sangram Anand


2 Answers

if you just want to compare then use this:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setCoalescing(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setIgnoringComments(true);
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc1 = db.parse(new File("file1.xml"));
doc1.normalizeDocument();

Document doc2 = db.parse(new File("file2.xml"));

doc2.normalizeDocument();
Assert.assertTrue(doc1.isEqualNode(doc2));

else see this http://xmlunit.sourceforge.net/

like image 191
Zaz Gmy Avatar answered Sep 19 '22 04:09

Zaz Gmy


I would go for the XMLUnit. The features it provides :

  • the differences between two pieces of XML
  • The outcome of transforming a piece of XML using XSLT
  • The evaluation of an XPath expression on a piece of XML
  • The validity of a piece of XML
  • Individual nodes in a piece of XML that are exposed by DOM Traversal

Good Luck!

like image 44
aviad Avatar answered Sep 17 '22 04:09

aviad