Comparing two xml files using JAVA

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

Thank.

+5
source share
7 answers

I would go for XMLUnit . Functions that it provides:

  • differences between two parts of XML
  • Result of transforming part of XML using XSLT
  • Evaluating an XPath Expression on an XML Fragment
  • XML
  • XML, DOM Traversal

!

+5

, :

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 . http://xmlunit.sourceforge.net/

+12

JAXB Java XML, Java. .

+4

, , , , "" .

XML- XML , JAXB, , DOM, XML-. , XML , , .

, , "" (, ).

, Java, Set ( )

, .

+3

, , Guiffy

. , DOM, 2 DOM .

+1

:

(a), , ? , , , , , , XML?

(b) ? (i) : /, (ii) , , (iii) , .

, : (a) Canonical XML . . (b) , () saxon: deep-equal(). , , ( , ).

If you want to write Java code, you can, of course, implement your own comparison logic - for example, you could find an open source XPath implementation and modify it to suit your requirements. This is just a hundred lines of code.

+1
source

it's a bit overkill, but if your XML has a schema, you can convert it to an EMF metamodel, and then use EMF Compare to compare.

0
source

All Articles