Java – JAXB Unmarshaller – Unexpected element Exception

javajaxbparsingunmarshallingxml

I'm using the JAXB parser to convert XML sent via an http request to a Java object while validating it against my XSD schema. The problem is that when the unmarshal() method is called it raises this exception:

javax.xml.bind.UnmarshalException: unexpected element
(uri:"http://www.somedomain.com/", local:"assign"). Expected elements
are (none)

If I remove the namespace from my root XML element it raises the same exception with the uri portion being empty:

javax.xml.bind.UnmarshalException: unexpected element
(uri:"", local:"assign"). Expected elements
are (none)

The unmarshalling code:

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

My Java class and 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)

The XML I'm trying to parse:

<?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>

If anyone could tell me where I'm going wrong, it'd be much appreciated!

Best Answer

You will need an @XmlRootElement annotation on your AssignType class. You'll probably also want to add name=patientAssign to your patient instance variable.

Related Topic