xmlunit

XMLUNIT 2 using comparison with ignore element order with diffbuilder and namespaces fails


I am trying to use DiffBuilder to ignore XML elements order when comparing two .xml files but it fails. I have tried every possible combination and read many articles before posting this question.

For example:

<Data:Keys>
 <Data:Value Key="1" Name="Example1" />
 <Data:Value Key="2" Name="Example2" />
 <Data:Value Key="3" Name="Example3" />
</Data:Keys>

<Data:Keys>
 <Data:Value Key="2" Name="Example2" />
 <Data:Value Key="1" Name="Example1" />
 <Data:Value Key="3" Name="Example3" />
</Data:Keys>

I want these two treated as same XML. Notice that elements are empty, they have only attributes. What I did so far:

def diff = DiffBuilder.compare(Input.fromString(xmlIN))
           .withTest(Input.fromString(xmlOUT))
           .ignoreComments()
           .ignoreWhitespace()
           .checkForSimilar()
           .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.conditionalBuilder()
           .whenElementIsNamed("Data:Keys").thenUse(ElementSelectors.byXPath("./Data:Value", 
            ElementSelectors.byNameAndText))
           .elseUse(ElementSelectors.byName)
           .build()))

But it fails every time. I don't know if the issue is the namespace, or that the elements are empty.

Any help will be appricated. Thank you in advance.


Solution

  • if you aim to match tags Data:Value by their attributes together, you should start with this:

    .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.conditionalBuilder()
               .whenElementIsNamed("Data:Value") 
    

    and since that tag doesn't have any text, the byNameAndText won't work. You can only work on names and attributes. My advice is to do it like this:

    .thenUse(ElementSelectors.byNameAndAttributes("Key"))
    

    or

    .thenUse(ElementSelectors.byNameAndAllAttributes()) 
    //equivalent
    .thenUse(ElementSelectors.byNameAndAttributes("Key", "Name"))
    

    As of issues with namespaces, checkForSimilar() should output SIMILAR, this means they are not DIFFERENT, so this is what you need. If you didn't use checkForSimilar() the differences in namespaces would be outputed as DIFFERENT.