Xetius
Xetius

Reputation: 46794

How to marshall a list of strings

Given the following XML:

<Location xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Exits>
    <string>/Maze/Location/easy/00f744f5-9737-4460-9791-9b44013346b7</string>
  </Exits>
  <LocationId>ebd65e24-ec5a-4105-8738-192da75b46eb</LocationId>
  <LocationType>Start</LocationType>
</Location>

I am trying to marshall the XML into the following pojo:

@XmlRootElement(name = "Location")
public class Location {
    private List<String> exits = new ArrayList<String>();
    private String locationId;

    @XmlElement(name = "Exits")
    public void setExits(List<String> exits) {
        this.exits = exits;
    }

    public List<String> getExits() {
        return exits;
    }
    private String locationType;

    @XmlElement(name = "LocationId")
    public void setLocationId(String locationId) {
        this.locationId = locationId;
    }

    public String getLocationId() {
        return locationId;
    }

    @XmlElement(name = "LocationType")
    public void setLocationType(String locationType) {
        this.locationType = locationType;
    }

    public String getLocationType() {
        return locationType;
    }
}

The values for locationId and locationType get set, but it is not parsing the list of "Exits" into the corresponding List in the object. Currently the Exits list contains a single entry with "\n" instead of "/Maze/Location/easy/00f744f5-9737-4460-9791-9b44013346b7"

How do I configure the pojo to parse this correctly.

I'm using Spring and JaxB.

Upvotes: 1

Views: 86

Answers (1)

Max Fichtelmann
Max Fichtelmann

Reputation: 3504

@XmlElementWrapper does the trick to wrap all elements of a list into another element.

@XmlElementWrapper(name="Exits")
@XmlElement(name = "string")
public void setExits(List<String> exits) {
    this.exits = exits;
}

Upvotes: 2

Related Questions