How can I programmatically determine the difference between two XML files as XPATH using Java?

StackOverflow https://stackoverflow.com/questions/21428016

  •  04-10-2022
  •  | 
  •  

Question

Given two XML documents, I would like to programmatically identify where the documents differ, and extract the locations of the differences as a list of XPath expressions.

I would like to do it using Java.

I would also like the definition of 'difference' to be somewhat configurable (i.e. similar vs identical - in terms of whitespace/formatting, empty simple elements etc.)

I assume that I can use something akin to XMLUnit, but if I understand correctly as a testing tool XMLUnit only identifies that there is a difference, but does not expose the details in a way that can be used programmatically.

Was it helpful?

Solution

Actually, it looks like it can be done using XMLUnit, by overriding the DifferenceListener.

    final List<String> xpaths = new ArrayList<String>();

    DifferenceListener myDifferenceListener = new DifferenceListener() {

        public void skippedComparison(Node arg0, Node arg1) {
            // Do nothing
        }

        public int differenceFound(Difference pDifference) {
            xpaths.add(pDifference.getControlNodeDetail().getXpathLocation());
            return RETURN_ACCEPT_DIFFERENCE;
        }
    };

    Diff myDiff = new Diff(xmlDoc1, xmlDoc2);
    myDiff.overrideDifferenceListener(myDifferenceListener);
    myDiff.similar();
    return paths;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top