我正在使用 JAXB 解析器将通过 http 请求发送的 XML 转换为 Java 对象,同时根据我的 XSD 模式对其进行验证。问题是,当调用 unmarshal() 方法时,它会引发此异常:
javax.xml.bind.UnmarshalException:意外元素(uri:“ http://www.somedomain.com/ ”,本地:“assign”)。预期元素是(无)
如果我从根 XML 元素中删除命名空间,则会引发相同的异常,其中 uri 部分为空:
javax.xml.bind.UnmarshalException:意外元素(uri:“”,本地:“分配”)。预期元素是(无)
解组代码:
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>
如果有人能告诉我哪里出错了,将不胜感激!