![](/img/trans.png)
[英]How to Unmarshaller XML by JAXB where parent and child node as same name
[英]jaxb unMarshaller failure ClassCastException because two xml elements are the same name. Why?
我的解组员遇到问题。 我有一个如下文件:
<Employee xmlns="namespace here">
<Employee>
<Id>2</Id>
<Name>idk</Name>
</Employee>
</Employee>
问题是根元素和元素列表具有相同的名称“ Employee”。 当我去编组时,我得到了classcastexception。
@XmlRootElement(name="Employee")
public class EmployeeInformation {
List<EmployeeInformationElement> elements;
private String errorCode;
private String errorMessage;
public List<EmployeeInformationElement> getElements() {
return elements;
}
@XmlElement(name="Employee")
public void setElements(List<EmployeeInformationElement> elements) {
this.elements = elements;
}
public String getErrorCode() {
return errorCode;
}
@XmlElement(name="ErrorCode")
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
@XmlElement(name="ErrorMessage")
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
我能够使用此代码封送一个看起来与我需要封送的文件完全一样的文件。 所以我很困惑。 缺少什么,所以当我解组时,解组器不会给我以下异常:
java.lang.ClassCastException: XXXX.EmployeeInformationElement cannot be cast to XXXX.EmployeeInformation
无法复制(在Java 1.8.0_65上测试)。
由于您未提供MCVE (最小,完整和可验证的示例),因此可以使用此方法。
唯一已知的区别是名称空间已删除,以便进行简单测试。
import java.io.StringReader;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
public class Test {
public static void main(String[] args) throws Exception {
String xml = "<Employee>\r\n" +
"<Employee>\r\n" +
" <Id>2</Id>\r\n" +
" <Name>idk</Name>\r\n" +
"</Employee>\r\n" +
"</Employee>\r\n";
JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeInformation.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
EmployeeInformation empInfo = (EmployeeInformation)unmarshaller.unmarshal(new StringReader(xml));
System.out.println(empInfo);
}
}
@XmlRootElement(name="Employee")
class EmployeeInformation {
private List<EmployeeInformationElement> elements;
@XmlElement(name="Employee")
public List<EmployeeInformationElement> getElements() {
return elements;
}
public void setElements(List<EmployeeInformationElement> elements) {
this.elements = elements;
}
}
class EmployeeInformationElement {
private int id;
private String name;
@XmlElement(name="Id")
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement(name="Name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.