使用XMLUnit绕过元素的顺序比较两个xml [英] Compare two xml's using XMLUnit bypassing the order of elements

查看:337
本文介绍了使用XMLUnit绕过元素的顺序比较两个xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个比较实用程序,它使我可以在不考虑顺序的情况下比较两个xml的相似性.我正在使用xmlunit 2.4.0

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();

因此,下面的两个xml成功进行了比较

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>

但是,当我输入以下内容时,此操作将失败: xml1:

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>

我尝试创建ElementSelector,即使那样也无济于事.

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();

推荐答案

您的XPath不匹配任何内容.

Your XPath doesn't match anything.

上下文."是您使用whenElementIsNamed选择的节点,因此它是相应的花朵"元素.

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

您的意思可能是"./flower"-在您的示例中没有发现任何差异.

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

这篇关于使用XMLUnit绕过元素的顺序比较两个xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆