【问题标题】:Parsing XML to java Object containing List attributtes将 XML 解析为包含列表属性的 java 对象
【发布时间】:2018-06-13 18:13:31
【问题描述】:

我很难将 xml 文件转换为 java 对象,并希望获得一些帮助。问题如下:

我有一个 Server 类,它有 2 个名为 UserListEventList 的子类。

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)}}

我的错误在哪里?

【问题讨论】:

  • 您的EventStand 和其他java 类真的在default 包中吗(没有package 声明)?以及您的 XML 没有定义命名空间?
  • 我的 Event Stand 类在模型包中,我的解析 XML 的代码在主类 ui 包中。

标签: java xml parsing


【解决方案1】:

我认为您也需要对 Stand 类进行注释。

类似这样(班级成员根据您的预期输出猜测):

@XmlRootElement
public class Stand {
@XmlElement
private String descri;
@XmlElement
private double area;
@XmlElement
private List<RelativeDistanceSet> relativeDistanceSet;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2017-11-07
    相关资源
    最近更新 更多