Search code examples
javaxmlxmlunit

Matching tags with identical names but different child values


I am trying to use XMLUnit 2 to compare xml files.

<composite>
    <data>
        <subtag>
            <code>1</code>
        </subtag>
        <subtag>
            <code>2</code>
        </subtag>
    </data>
</composite>

Second file is the same, with the only difference being 'subtag' tags switched places.

<composite>
    <data>
        <subtag>
            <code>2</code>
        </subtag>
        <subtag>
            <code>1</code>
        </subtag>
    </data>
</composite>

I've been out of luck so far finding a set of ElementMatchers suitable to match those two as equal.

Is there an out of the box solution for this problem?


Solution

  • This is pretty much identical to the "tr is identified by nested th" example from XMLUnit's user-guide. One solution is to use a conditional ElementSelector and ensure it uses the correct rule when deciding which subtag to take - see https://github.com/xmlunit/user-guide/wiki/SelectingNodes#conditional-elementselectors

    In your concrete case something like

    ElementSelectors.conditionalBuilder()
        .whenElementIsNamed("subtag")
        .thenUse(ElementSelectors.byXPath("./code", ElementSelectors.byNameAndText))
        .elseUse(ElementSelectors.byName)
        .build();
    

    should do. This assumes your subtags are identified by the nested text of their code child element.