Is it valid to specify xsi:type for an local complexType?

别说谁变了你拦得住时间么 提交于 2019-12-06 11:30:52

Is Your XML Document Valid?

No, as you state the value of the xsi:type attribute does not correspond to a named complex type in your XML schema.

Should that Matter?

JAXB implementations aim to be very fault tolerant. I couldn't get your example to fail using the default JAXB impl in the latest JDK 1.7 install or EclipseLink JAXB (MOXy):

ErRequest

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="er-request")
public class ErRequest {

}

Demo

import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(ErRequest.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource xml = new StreamSource("src/forum22497112/input.xml");
        ErRequest erRequest = (ErRequest) unmarshaller.unmarshal(xml);

    }

}

Where is the Error Coming From

The error you are getting appears to be a schema validation error:

Error::cvc-elt.4.2: Cannot resolve 'er-request' to a type definition for element 'er-request'

Are you asking JAXB to perform schema validation on the input? JAXB does not do this by default. Since your document is not valid you will have to fix it or register an error listener to ignore it.

You need to promote the anonymous complex type to a global (named) type:

<xs:element name="er-request" type="er-request"/>

<xs:complexType name="er-request">
        <xs:sequence>
            <xs:element name="payload" type="payloadType" minOccurs="0"/>
        </xs:sequence>
        <xs:attribute name="id" use="required">
            <xs:simpleType>
                <xs:restriction base="xs:int"/>
            </xs:simpleType>
        </xs:attribute>
</xs:complexType>

Alternatively, just remove the xsi:type attribute. It's not doing anything useful here since the element name is enough to identify the required type.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!