【问题标题】:Java XMLUnit comparing XML-files with different information orderingJava XMLUnit 比较具有不同信息排序的 XML 文件
【发布时间】:2015-03-26 08:55:57
【问题描述】:

我正在尝试验证和检查两个 XML 文件之间的差异。

XML 文件 1:

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

XML 文件 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 [不同] 预期的属性值 'Foo' 但为 'Bar' - 比较 在 /message[1]/Customer[1]/Description[1]/@description 到 /message[1]/Customer[1]/Description[1]/@description

这里是 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);
    }
}

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

【问题讨论】:

    标签: java xml junit compare xmlunit


    【解决方案1】:

    你可以试试这个。

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

    【讨论】:

    • 我也有xml元素的属性来相互比较,而不仅仅是结构
    【解决方案2】:

    我通过添加解决了它:

    Diff diff = new Diff(doc1, doc2);
    diff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
    XMLAssert.assertXMLEqual(diff, Boolean.TRUE);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多