20

The docs state the the @XmlElementWrapper annotation can be used for 'unwrapped' or 'wrapped' collections.

http://docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/XmlElementWrapper.html

How do you configure it to produce an unwrapped collection?

1 Answer 1

38

If you include @XmlElementWrapper it will add a grouping element:

@XmlElementWrapper
@XmlElement(name="foo")
public List<Foo> getFoos() {
    return foos;
}
<root>
    <foos>
        <foo/>
        <foo/>
    </foos>
</foo>

and if you omit it, then it won't.

@XmlElement(name="foo")
public List<Foo> getFoos() {
    return foos;
}
<root>
    <foo/>
    <foo/>
</foo>

For More Information

5
  • 1
    The documentation suggests that the @XmlElementWrapper supports two forms: "The annotation therefore supports two forms of serialization shown below." It seems to imply that we can configure this annotation to produce an unwrapped collection. Your example omits the annotation altogether.
    – timmy
    Apr 30, 2013 at 16:04
  • @user106563 - The documentation may need to be cleaned up, can you share the link you are referring to? If you add the @XmlElementWrapper annotation there will always be a grouping element (as long as the value is not null).
    – bdoughan
    Apr 30, 2013 at 16:39
  • Check out the first paragraph of the following link: docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/…
    – timmy
    Apr 30, 2013 at 19:20
  • 3
    @user106563 - I agree that javadoc is confusing. In reality @XmlElementWrapper works as I described. FWIW I'm a member of the JAXB (JSR-222) expert group and you can find my name in the spec: jcp.org/en/jsr/detail?id=222
    – bdoughan
    Apr 30, 2013 at 20:34
  • This solution has one drawback. When changing to JSON, the name of the list becomes the name given in @XmlElement (aka, the singular). Any idea on how to circumnavigate this? Oct 8, 2020 at 21:52

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.