Search code examples
javajaxbjaxb2

How to marshall a set with jaxb?


I have the following code:

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

   @XmlElement
   private String id;

   ...

}

I would like to be able to marshal a Set<Foo> foos into:

<foos>
   <foo>
       <id>bar1</id>
   </foo>
   <foo>
       <id>bar2</id>
   </foo>
</foos>

Do I need a wrapper class? If so, how should it look? Are my annotations correct? How should the marhalling code look like (if you could illustrate this all, that'd be much appreciated)?


Solution

  • If you want to encapsulate any Collection use XmlElementWrapper

    @XmlElementWrapper(name="foos")
    @XmlElement(name="foo")
    private Set<Foo> foos;
    

    By the way you cannot directly marshall a Set so you have to include your Set inside your own class. So if you just want to marshall a set of Foo you have to write a bean like this :

    @XmlRootElement(name = "foos")
    public class Foos {
        @XmlElement(name="foo")
        private Set<Foo> foo;
    }