简体   繁体   English

使用JAXB将同名的多个XML元素解组到列表中

[英]Unmarshalling multiple XML elements of the same name into a list using JAXB

I'm attempting to unmarshall an XML message into a Java Object. 我正在尝试将XML消息解组为Java对象。 I have it working for the most part but there is one issue I'm stuck on. 我有大部分工作,但有一个问题我坚持下去。 I have a schema that looks like this: 我有一个如下所示的架构:

<DeliveryDetails>
  <Name>Ed</Name>
  <Location>Toronto</Location>
  <Event>
    <Date>2013-05-06</Date>
    <Time>12:12</Time>
    <Description>MARKHAM</Description>
  </Event>
  <Event>
    <Date>2013-05-07</Date>
    <Time>05:12</Time>
    <Description>MARKHAM</Description>
  </Event>
  <Event>
    <Date>2013-05-08</Date>
    <Time>15:12</Time>
    <Description>MARKHAM</Description>
  </Event>
</DeliveryDetails>

Now, the issue is that the JAXB ObjectFactory is only saving the last event. 现在,问题是JAXB ObjectFactory只保存最后一个事件。 If there was an element wrapping the events ( ), then I would know how to handle it using an XML Element Wrapper. 如果有一个元素包装events(),那么我将知道如何使用XML Element Wrapper处理它。 But since there is no wrapper, I'm not sure what to do. 但由于没有包装,我不知道该怎么办。 Anybody have any ideas? 有人有什么想法吗?

I'm guessing the ObjectFactory is getting all the events but constantly overwriting the old one with the newest one. 我猜测ObjectFactory正在获取所有事件,但不断用最新的事件覆盖旧事件。 There needs to be some way to tell it to save each individual event instead of just writing over the same one every time, but I don't know how to accomplish that. 需要有一些方法来告诉它保存每个单独的事件,而不是每次只写同一个事件,但我不知道如何实现这一点。

By default a JAXB (JSR-222) implementation will represent a List as multiple elements with the same name. 默认情况下, JAXB(JSR-222)实现将List表示为具有相同名称的多个元素。 As long as you have something like the following you will be fine: 只要您拥有以下内容,您就可以了:

@XmlRootElement(name="DeliveryDetails")
@XmlAccessorType(XmlAccessType.FIELD)
public class DeliveryDetails {

    @XmlElement(name="Name")
    private String name;

    @XmlElement(name="Location")
    private String location;

    @XmlElement(name="Event")
    private List<Event> events;

}

For More Information 欲获得更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM