将XML解析为包含列表属性的java对象
我在将xml文件转换为java对象时遇到了难题,希望获得一些帮助。问题如下:
我有一个Server类,它有两个子类,分别名为UserList和EventList
(UserList包含用户列表)和EventList事件列表
我应该从包含类事件实例及其所有信息的文件中读取信息。我的课堂事件定义如下:
@XmlRootElement
public class Event {
@XmlElement
private String title;
@XmlElement
private List<Stand> stands;
public Event(String title, List<Stand> stands) {
this.title = title;
this.stands = stands;
}
在我的主要课程中,我试图用JAXBContext解压xml:
JAXBContext jaxbContext = JAXBContext.newInstance(Event.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
File file = new File("exhibition1_v0.1.xml");
Event event = (Event) unmarshaller.unmarshal(file);
System.out.println("Event name :" +event.getTitle());
for( Stand s: event.getStands()){
System.out.println(s);
}
示例XML文件有一个示例支架:
<event>
<title>exhibition1</title>
<stands>
<stand>
<description>Stand 1</description>
<area>37</area>
<relativeDistanceSet>
<distance>
<description>Stand 2</description>
<value>9</value>
</distance>
<distance>
<description>Stand 3</description>
<value>7</value>
</distance>
<distance>
<description>Stand 4</description>
<value>12</value>
</distance>
</relativeDistanceSet>
</stand>
</stands>
.....
我得到以下输出:
Event name : exhibition1
Stand{descri=null, area=0.0, relativeDistanceSet=null}
应该得到:
Event name : exhibition1
Stand{descri=Stand1, area=37.0, relativeDistanceSet={(description=Stand2, value=9),(description=Stand3, value=7),(description=Stand4, value=12)}}
我的错误在哪里
# 1 楼答案
我认为你也需要为班级立场做注解
类似这样的内容(类成员根据您的预期输出猜测):