javaxmljunitxmlunit

How do I ignore certain elements when comparing XML?


I have an XML message like so:

<root>
  <elementA>something</elementA>
  <elementB>something else</elementB>
  <elementC>yet another thing</elementC>
</root>

I want to compare a message of this type produced by a method under test to an expected message, but I don't care about elementA. So, I'd like the above message to be considered equal to:

<root>
  <elementA>something different</elementA>
  <elementB>something else</elementB>
  <elementC>yet another thing</elementC>
</root>

I'm using the latest version of XMLUnit.

I'm imagining that the answer involves creating a custom DifferenceListener; I just don't want to reinvent the wheel if there's something ready to use out there.

Suggestions that use a library other than XMLUnit are welcome.


Solution

  • Things have changed a lot for XMLUnit since this question was answered.

    You can now easily ignore a node when using a DiffBuilder:

    final Diff documentDiff = DiffBuilder
                .compare(expectedSource)
                .withTest(actualSource)
                .withNodeFilter(node -> !node.getNodeName().equals(someName))
                .build();
    

    If you then call documentDiff.hasDifferences() nodes added to filter will be ignored.