Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 597
Paul Morie Avatar asked Aug 06 '09 21:08

Paul Morie


People also ask

What is XMLUnit?

XMLUnit provides you with the tools to verify the XML you emit is the one you want to create. It provides helpers to validate against an XML Schema, assert the values of XPath queries or compare XML documents against expected outcomes.


1 Answers

I wound up implementing a DifferenceListener that takes a list of node names (with namespaces) to ignore textual differences for:

public class IgnoreNamedElementsDifferenceListener implements DifferenceListener {     private Set<String> blackList = new HashSet<String>();      public IgnoreNamedElementsDifferenceListener(String ... elementNames) {         for (String name : elementNames) {             blackList.add(name);         }     }      public int differenceFound(Difference difference) {         if (difference.getId() == DifferenceConstants.TEXT_VALUE_ID) {             if (blackList.contains(difference.getControlNodeDetail().getNode().getParentNode().getNodeName())) {                 return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;             }         }          return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;     }      public void skippedComparison(Node node, Node node1) {      } } 
like image 161
Paul Morie Avatar answered Sep 22 '22 19:09

Paul Morie