JAXB Unmarshaller - 意外的元素异常

时间:2013-05-29 13:36:08

标签: java xml parsing jaxb unmarshalling

我正在使用JAXB解析器将通过http请求发送的XML转换为Java对象,同时根据我的XSD架构验证它。问题是当调用unmarshal()方法时会引发此异常:

  

javax.xml.bind.UnmarshalException:意外元素   (uri:“http://www.somedomain.com/”,local:“assign”)。预期的要素   是(无)

如果我从我的根XML元素中删除命名空间,则会在uri部分为空时引发相同的异常:

  

javax.xml.bind.UnmarshalException:意外元素   (uri:“”,local:“assign”)。预期的要素   是(无)

解组码:

            ServletInputStream xmlFile = request.getInputStream();

            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File("PatientAssignment.xsd"));

            JAXBContext jc = JAXBContext.newInstance(AssignType.class);

            Unmarshaller unmarshaller = jc.createUnmarshaller();
            unmarshaller.setSchema(schema);
            unmarshaller.setEventHandler(new AssignValidationEventHandler(patientResponses));
            assignments = (AssignType) unmarshaller.unmarshal(xmlFile);

我的Java类和package-info.java:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AssignType", namespace = "http://www.somedomain.com/", propOrder = {
    "patient"
})
public class AssignType {
    @XmlElement(namespace = "http://www.somedomain.com/", required = true)
    protected List<PatientAssignType> patient;

    /* Getters and setters ommitted */
}

// package-info.java
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.somedomain.com/", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)

我正在尝试解析的XML:

<?xml version="1.0" encoding="UTF-8"?>
<assign xmlns="http://www.somedomain.com/">
    <patientAssign xmlns="http://www.somedomain.com/">
        <firstName>Buddy</firstName>
        <lastName>Holly</lastName>
        <email></email>
        <dob></dob>
        <phone></phone>
                ...
    </patientAssign>
</assign>

如果有人能告诉我哪里出错了,我们将非常感激!

1 个答案:

答案 0 :(得分:4)

您的@XmlRootElement课程需要AssignType注释。您可能还想将name=patientAssign添加到患者实例变量中。