Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

xml

jaxb

I'm attempting to unmarshall an XML message into a Java Object. 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. If there was an element wrapping the events ( ), then I would know how to handle it using an 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. 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.

like image 537
UpAllNight Avatar asked Feb 17 '23 10:02

UpAllNight


1 Answers

By default a JAXB (JSR-222) implementation will represent a List as multiple elements with the same name. 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

  • http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html
like image 123
bdoughan Avatar answered Apr 07 '23 21:04

bdoughan