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
Java: Syntax and Meaning Behind "[B@1Ef9157"? Binary/Address
What Is the Cost of Calling Array.Length
How to Create a Jandex Index in Quarkus for Classes in a External Module
Most Efficient Conversion of Resultset to JSON
Embed Java into a C++ Application
Interview Question: Check If One String Is a Rotation of Other String
How to Get the Intersection Between Two Arrays as a New Array
Why We Use If, Else If Instead of Multiple If Block If the Body Is a Return Statement
What Is More Efficient, I++ or ++I
What's the C++ Idiom Equivalent to the Java Static Block
Why Are Strings Immutable in Many Programming Languages
Proper Implementation of Cubic Spline Interpolation
What Is Ld_Library_Path and How to Use It
Convert HTML Character Back to Text Using Java Standard Library
Pure Java HTML Viewer/Renderer for Use in a Scrollable Pane