I'm having a problem comparing various elements in my xml document with XMLUnit (2.2.1). In my document there are several xml elements and I want to know, whether they differ from each other. However, I don't want to compare all xml elements the same way. Sometimes I just want to compare them by their name.In other cases I want to compare them by name and attribute or name and text.
Here is an example (see the comments)
Control
<?xml version="1.0" encoding="UTF-8"?>
<ROOT>
<LANGUAGES>
<!-- Compare LANGUAGE by Name and Attribute -->
<LANGUAGE VALUE="DE" />
<LANGUAGE VALUE="EN" />
<LANGUAGE VALUE="IT" />
<LANGUAGE VALUE="FR" />
</LANGUAGES>
<CODES>
<!-- Compare CODE by Name and Text -->
<CODE>10000-1</CODE>
<CODE>20000-2</CODE>
<CODE>30000-3</CODE>
<CODE>40000-4</CODE>
</CODES>
<CONTACT> <!-- Compare CONTACT and Children just by Name -->
<FIRSTNAME>Max</FIRSTNAME>
<SURNAME>Mustermann</SURNAME>
</CONTACT>
</ROOT>
Test:
<?xml version="1.0" encoding="UTF-8"?>
<ROOT>
<LANGUAGES>
<!-- Compare LANGUAGE by Name and Attribute -->
<LANGUAGE VALUE="DE" />
<LANGUAGE VALUE="FR" />
</LANGUAGES>
<CODES>
<!-- Compare CODE by Name and Text -->
<CODE>20000-2</CODE>
<CODE>40000-4</CODE>
</CODES>
<CONTACT> <!-- Compare CONTACT and Children by Name -->
<FIRSTNAME>Tim</FIRSTNAME>
<SURNAME>Mustermann</SURNAME>
</CONTACT>
</ROOT>
I tried ElementSelectors in combination with ElementSelectors.conditionalBuilder (https://github.com/xmlunit/user-guide/wiki/SelectingNodes#conditional-elementselectors) to only apply an ElementSelector on a specific element (whenElementIsNamed). Maybe this isn't the right approach for what I want to achieve.
This is my code I use for testing:
public void xmlDiff() {
String control = getControlDocument(); //
String test = getTestDocument(); //
Diff myDiff = DiffBuilder.compare(control)//
.withTest(test) //
.ignoreWhitespace() //
.ignoreComments() //
.checkForSimilar() //
.withNodeMatcher(new DefaultNodeMatcher(partialElementSelector("LANGUAGE", ElementSelectors.byNameAndAllAttributes), partialElementSelector("CODE",ElementSelectors.byNameAndText), ElementSelectors.byName)) //
.build();
assertThat(myDiff.hasDifferences()).isTrue(); //
}
private ElementSelector partialElementSelector(final String expectedName, final ElementSelector elementSelector) {
return ElementSelectors.conditionalBuilder().whenElementIsNamed(expectedName).thenUse(elementSelector).build();
}
What I actually need is the information, that two LANGUAGEs (EN,IT) and two CODEs (10000-1,30000-3) have been removed (not replaced) and FIRSTNAME changed.
How can I get those information, with or without XML Unit (DiffBuilder)?
Thank you for your help!