有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

比较两个XML响应的JavaXMLUnit

expectedResponseXml 1:

<?xml version="1.0" encoding="UTF-8"?>
<GetResponse xmlns="http://whatever.co.uk/xsd/nam/message/GetResponse/">
    <Success>
        <Case>
            <Mort>M123456</Mort>
            <Appl>01</Appl>
        </Case>
        <Decision>D</Decision>
        <ProcessingRoute>R</ProcessingRoute>
        <Score>99999</Score>
    </Success>
</GetResponse>

以及实际响应EXML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<GetResponse xmlns:ns2="http://whatever.co.uk/xsd/nam/message/GetResponse/"> 
    <ns2:Success> 
        <ns2:Case> 
            <ns2:Mort>M123456</ns2:Mort> 
            <ns2:Appl>01</ns2:Appl> 
        </ns2:Case> 
        <ns2:Decision>D</ns2:Decision> 
        <ns2:ProcessingRoute>R</ns2:ProcessingRoute> 
        <ns2:Score>99999</ns2:Score> 
    </ns2:Success> 
</GetResponse>

错误消息是:

Expected child 'GetResponse' but was 'null' - comparing <GetResponse...> at /GetResponse[1] to <NULL>

比较代码:

Diff myDiffSimilar = DiffBuilder.compare(Input.fromString(actualResponseXml))
                                        .withTest(Input.fromString(expectedResponseXml))
                                        .checkForSimilar()
                                        .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName))
                                        .build();

我已经尝试了各种方法,从XMLUnit的官方github帐户到几个类似的问题来修复这个错误,我觉得这是名称空间中的一个差异,应该被differenceEngine忽略。从上面的代码中,我通过两个XML的字符串表示形式比较了它们。当我取出checkForSimilar()时,我得到了这个错误

Expected namespace uri 'null' but was 'http://whatever.co.uk/xsd/nam/message/GetResponse/'

我对maven的依赖是

<dependency>
    <groupId>org.xmlunit</groupId>
    <artifactId>xmlunit-legacy</artifactId>
    <version>2.5.0</version>
    <scope>test</scope>
</dependency>

我们将非常感谢您的帮助


共 (1) 个答案

  1. # 1 楼答案

    在解决了上面这些人正确提到的名称空间问题后,我发现了问题所在。 将jaxb对象编组为XML时,请避免使用QName(localPart)构造函数,因为这会给不可预测的问题带来文档中已知和提到的问题

    In an XML context, all Element and Attribute names exist in the context of a Namespace. Making this explicit during the construction of a QName helps prevent hard to diagnosis XML validity errors. The constructors QName(String namespaceURI, String localPart) and QName(String namespaceURI, String localPart, String prefix) are preferred. link here


    为什么会这样对我来说是个奇迹!!使用

    marshaller.marshal(new JAXBElement(new QName(namespaceURI, localPart, NS_PREFIX), jaxbObject.getClass(), jaxbObject), outputStream);
    

    在marshaller上删除不需要的名称空间并将其设置为默认值