1
我無法用JAXB解組簡單的元素列表。我進一步簡化了模型,仍然存在問題。JAXB解組列表
我有2個元素類,一個Classroom元素和一個Student元素。我曾經模仿他們在Java中象下面這樣:
@XmlRootElement(name = "classroom", namespace = "http://www.info.com/school/model")
@XmlAccessorType(XmlAccessType.FIELD)
public class Classroom {
@XmlElementWrapper(name = "students")
@XmlElement(name = "student", type = Student.class)
private List<Student> students;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {
private String name;
private String gender;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
當我嘗試解編教室的元素,它是無法解組學生名單。例如,下面的代碼應該輸出到System out「學生數量是2」,但是當我運行它時,我得到「學生數量是:0」。
有人能夠指出我正確配置JAXB註釋的方向,以便我可以解組嗎?
我甚至在JAXB上下文中添加了一個toString方法調用,我可以看到Student類也列出了。
public static void main(String[] args) {
SimpleJaxbTestForLists sjtfl = new SimpleJaxbTestForLists();
sjtfl.unmarshal("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><classroom xmlns=\"http://www.info.com/school/model\"><students><student><name>Test Student 1</name><gender>Male</gender><age>12</age></student><student><name>Test Student 2</name><gender>Female</gender><age>12</age></student></students></classroom>");
}
public void unmarshal(String xmlContent) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Classroom.class);
System.out.println(jaxbContext.toString());
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(xmlContent);
Classroom classroom = (Classroom) jaxbUnmarshaller.unmarshal(reader);
System.out.println("Number of Pupils is: " + classroom.getStudents().size());
} catch (JAXBException ex) {
ex.printStackTrace();
}
}
我最近從這個博客:) – spiderman
@prash瞭解到 - 是你清楚如何,你需要使用'包info.java' ? –
嗨Blaise,我希望你會回答,一直在檢查你的博客尋求幫助,試圖解決這個問題,但沒有找到任何我認爲會幫助。不知道,或者想想這個XmlSchema註釋。謝謝!! –