0

我正在尝试验证和检查两个 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 与 at 进行比较/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);
    }
}

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

4

2 回答 2

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));
于 2015-03-26T10:06:03.653 回答
1

我通过添加解决了它:

Diff diff = new Diff(doc1, doc2);
diff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
XMLAssert.assertXMLEqual(diff, Boolean.TRUE);
于 2015-03-26T10:40:38.393 回答