【发布时间】:2018-06-13 18:13:31
【问题描述】:
我很难将 xml 文件转换为 java 对象,并希望获得一些帮助。问题如下:
我有一个 Server 类,它有 2 个名为 UserList 和 EventList 的子类。
(UserList 包含用户列表)和 EventList 事件列表。
我应该从包含 Event 类实例及其所有信息的文件中读取信息。我的班级Event定义如下:
@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;
}
在我的 Main 类中,我试图用 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)}}
我的错误在哪里?
【问题讨论】:
-
您的
Event、Stand和其他java 类真的在default包中吗(没有package声明)?以及您的 XML 没有定义命名空间? -
我的 Event Stand 类在模型包中,我的解析 XML 的代码在主类 ui 包中。