So, I needed a way to compare feature.xml files, but yet ignoring differences found in some xml attributes like "version", "download-size" and "install-size". Luckily, I stumbled upon XMLUnit, which saved me lots of efforts.
XMLUnit was designed as a helper for asserting test results for code that produces XML output. But it's also turns to be a great helper for any use case that involves comparison of XML data.
Comparing two XML files is as easy as creating a new Diff object and calling any of the two test methods: identical() and similar(). In my case, similar() worked better.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FileReader xml1 = ... | |
FileReader xml2 = ... | |
Diff xmlDiff = new Diff(xml1, xml2); | |
xmlDiff.similar(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
xmlDiff.overrideDifferenceListener( | |
new IgnoreVariableAttributesDifferenceListener()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class IgnoreVariableAttributesDifferenceListener implements | |
DifferenceListener { | |
private static final List<String> IGNORE_ATTRS = Arrays | |
.asList(new String[] { "version", "download-size", "install-size" }); | |
@Override | |
public int differenceFound(Difference difference) { | |
if (isIgnoredAttributeDifference(difference)) { | |
return RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR; | |
} else { | |
return RETURN_ACCEPT_DIFFERENCE; | |
} | |
} | |
@Override | |
public void skippedComparison(Node control, Node test) { | |
// nothing to do | |
} | |
private boolean isIgnoredAttributeDifference(Difference difference) { | |
return difference.getId() == DifferenceConstants.ATTR_VALUE_ID | |
&& IGNORE_ATTRS.contains(difference.getControlNodeDetail() | |
.getNode().getNodeName()); | |
} | |
} |