Best Way to Compare 2 Xml Documents in Java

Best way to compare 2 XML documents in Java

Sounds like a job for XMLUnit

  • http://www.xmlunit.org/
  • https://github.com/xmlunit

Example:

public class SomeTest extends XMLTestCase {
@Test
public void test() {
String xml1 = ...
String xml2 = ...

XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences

// can also compare xml Documents, InputSources, Readers, Diffs
assertXMLEqual(xml1, xml2); // assertXMLEquals comes from XMLTestCase
}
}

Comparing two xml files using JAVA

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!

Compare two xml files ignoring certain elements using xpath in Java

You need to transform both files into a form where they compare equal, by removing the elements you want to ignore. You would typically do this using XSLT. After the transformation you could either compare the results using the XPath 2.0 function deep-equal(), or serialise both documents as canonical XML and compare the files at the character or binary level.

UPDATE

Thanks for explaining the question more clearly.

I would do this by running XQuery Update to delete the nodes selected by the path expression, and then comparing the resulting documents either using fn:deep-equal(), or by doing canonical serialization and comparing the resulting lexical forms.

As an alternative to XQuery Update you could use xmlstarlet or Saxon's Gizmo tool.

But it might depend on what you want from the comparison. The above is fine if you want a yes/no answer, but getting details of the differences is more difficult. You could write your own query to find the differences, or use a tool such as DeltaXML.



Related Topics



Leave a reply



Submit