Search code examples
javajaxbjaxb2

How to marshall an unwrapped collection in JAXB?


This is my class:

@XmlRootElement(name = "foo")
@XmlAccessorType(XmlAccessType.NONE)
public class Foo {
  @XmlElement
  public Collection getElements() {
    List elements = new ArrayList();
    elements.add(new Bar);
    elements.add(new Bar);
    return elements;
  }
}

Class Bar is also simple:

@XmlType(name = "bar")
@XmlAccessorType(XmlAccessType.NONE)
public static final class Bar {
  @XmlElement
  public String getMessage() {
    return "hello, world!";
  }
}

This is what I'm getting after marshalling of Foo:

<foo>
  <elements xsi:type="foo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <message>hello, world!</message>
  </elements>
  <elements xsi:type="foo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <message>hello, world!</message>
  </elements>
</foo>

While I'm expecting to get:

<foo>
  <bar>
    <message>hello, world!</message>
  </bar>
  <bar>
    <message>hello, world!</message>
  </bar>
</foo>

What should I fix?


Solution

  • You will need to annotate the elements property with @XmlElement(name="bar"):

    @XmlRootElement(name = "foo")
    @XmlAccessorType(XmlAccessType.NONE)
    public class Foo {
      @XmlElement(name="bar")
      public Collection getElements() {
        List elements = new ArrayList();
        elements.add(new Bar);
        elements.add(new Bar);
        return elements;
      }
    }