Java XMLUnit将XML文件与不同的信息排序进行比较

时间:2015-03-26 08:55:57

标签: java xml junit compare xmlunit

我正在尝试验证并检查两个XML文件之间的区别。

XML文件1:

<Customer .....>
    <Description description="Foo" name="Foo" language="svSE"/>
    <Description description="Bar" name="Bar" language="enUS"/>
</Customer>

XML-file 2:

<Customer .....>
    <Description description="Bar" name="Bar" language="enUS"/>
    <Description description="Foo" name="Foo" language="svSe"/>
</Customer>

如您所见,两个文件中的描述值的顺序不同。但它们仍然是用于导入的合法XML文件。

当我在单元测试中尝试比较它们时,我得到以下断言错误:

  

junit.framework.AssertionFailedError:org.custommonkey.xmlunit.Diff   [不同]预期属性值&#39; Foo&#39;但是&#39; Bar&#39; - 比较    在   / message [1] / Customer [1] / Description [1] / @ description to at   /消息[1] /客户[1] /说明[1] / @描述

这是XmlUnit java代码:

public class FooTest extends AbstractTest {

    ...

    @Test
    public void assertFooBarFile() {

        ...

        XMLUnit.setIgnoreComments(Boolean.TRUE);
        XMLUnit.setIgnoreWhitespace(Boolean.TRUE);
        XMLUnit.setNormalizeWhitespace(Boolean.TRUE);
        XMLUnit.setIgnoreDiffBetweenTextAndCDATA(Boolean.TRUE);
        XMLUnit.setIgnoreAttributeOrder(Boolean.TRUE);
        XMLAssert.assertXMLEqual(doc1, doc2);
    }
}

关于如何比较这两个文件包含相同信息的任何想法(不关心生成信息的顺序)?

2 个答案:

答案 0 :(得分:0)

你可以试试这个。

public static boolean compareXMLs(String xmlSource, String xmlCompareWith)
        throws Exception {
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreComments(true);
XMLUnit.setIgnoreAttributeOrder(true);

XMLUnit.setNormalizeWhitespace(true);

Diff myDiff = new Diff(xmlSource, xmlCompareWith);
myDiff.similar()
}

测试

String x1 = "<a><a1/><b1/></a>";
String x2 = "<a><b1/><a1/></a>";
assertTrue(compareXMLs(x1, x2));

答案 1 :(得分:0)

我通过添加:

解决了这个问题
Diff diff = new Diff(doc1, doc2);
diff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
XMLAssert.assertXMLEqual(diff, Boolean.TRUE);