Compare two xml's using XMLUnit bypassing the order of elements

淺唱寂寞╮ 提交于 2020-01-16 08:44:27

问题


I am writing a comparison util which lets me compare similarity of two xmls without considering the order. Am using xmlunit 2.4.0

org.xmlunit.diff.Diff diff = DiffBuilder.compare(xml1)
                .withTest(xml2)
                .checkForSimilar()
                .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText))
                .build();

So with this, the below two xmls gets compared successfully

xml1:

<multistatus>
    <flowers>
        <flower>Roses</flower>
        <flower>Daisy</flower>
    </flowers>
    <flowers>
        <flower>Roses</flower>
        <flower>Daisy</flower>
    </flowers>
</multistatus>

xml2:

<multistatus>
    <flowers>
        <flower>Roses</flower>
        <flower>Daisy</flower>
    </flowers>
    <flowers>
        <flower>Daisy</flower>
        <flower>Roses</flower>
    </flowers>
</multistatus>

However this fails when i give the below input: xml1:

<multistatus>
    <flowers>
        <flower>Roses</flower>
    </flowers>
    <flowers>
        <flower>Daisy</flower>
    </flowers>
</multistatus>

xml2:

<multistatus>
    <flowers>
        <flower>Daisy</flower>
    </flowers>
    <flowers>
        <flower>Roses</flower>
    </flowers>
</multistatus>

I tried creating ElementSelector and even that is not helping.

ElementSelector selector = ElementSelectors.conditionalBuilder()
                .whenElementIsNamed("flowers").thenUse(ElementSelectors.byXPath("./flowers/flower", ElementSelectors.byNameAndText))
                .elseUse(ElementSelectors.byName)
                .build();

        org.xmlunit.diff.Diff diff = DiffBuilder.compare(refSource)
                .withTest(testSource)
                .checkForSimilar()
                .ignoreWhitespace()
                .normalizeWhitespace()
                .withNodeMatcher(
                        new DefaultNodeMatcher(
                                selector,ElementSelectors.Default)
                )
                .build();

回答1:


Your XPath doesn't match anything.

The context "." is the node you've selected with whenElementIsNamed so it is the respective "flowers" element.

You probably mean "./flower" - and it doesn't find any differences in your example.



来源:https://stackoverflow.com/questions/48216562/compare-two-xmls-using-xmlunit-bypassing-the-order-of-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!