gpt4 book ai didi

java - JAXB Unmarshaller - 意外的元素异常

转载 作者:数据小太阳 更新时间:2023-10-29 02:26:54 25 4
gpt4 key购买 nike

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

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

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

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

解码代码:

            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>

如果有人能告诉我哪里出错了,将不胜感激!

最佳答案

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

关于java - JAXB Unmarshaller - 意外的元素异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16815418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com