Archimedes Trajano
Archimedes Trajano

Reputation: 41230

How do you prevent JAXB from creating an intermediate object

I want to have the following XML

<doc>
   <items>
      <item />
      <item />
      <item />
   </items>
   <things>
      <thing />
      <thing />
      <thing />
   </things>
</doc>

The schema would be something like

<schema>
   <element name="doc">
      <complexType>
          <all>
              <element name="items" minOccurs="1">
                  <complexType>
                       <sequence>
                           <element name="item" minoccurs="0" maxoccurs="unbounded" />
                       </sequence>
                  </complexType>
              </element>
              <element name="things" minOccurs="1">
                  <complexType>
                       <sequence>
                           <element name="thing" minoccurs="0" maxoccurs="unbounded" />
                       </sequence>
                  </complexType>
              </element>
          </all>
      /<complexType>
   </element>
</schema>

Now with JAXB it creates a class called Doc which would have an Items type which has an Item. Therefor to add the first element I have to do this.

Doc doc = new Doc();
Items items = new Items();
items.getItem().add(new Item());
doc.setItems(items);

I would like to be able to do the following instead:

Doc doc = new Doc();
doc.getItems().add(new Item());

Or even better:

Doc doc = new Doc();
doc.addItem(new Item());

Anyway of doing this through JAXB bindings?

Upvotes: 1

Views: 209

Answers (3)

beerbajay
beerbajay

Reputation: 20270

Per the comment by nsfyn55, there does not seem to be any way to do this with bindings.

However, if you were using JAXB annoations, you could do:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Doc {
    @XmlElementWrapper(name = "items")
    @XmlElement(name="item")
    List<Item> items = new ArrayList<Item>();

    public void addItem(Item item) {
        this.items.add(item);
    }

    // ...
}

Upvotes: 4

Patrice M.
Patrice M.

Reputation: 4319

I would like to be able to do the following instead:

Doc doc = new Doc();

doc.getItems().add(new Item());

I believe that you can, (at least up to JAXB 2.1) the generated code for getItems() would check for a null member collection, and create it if necessary before returning it. So it always returns a 'live' list object.

Upvotes: 0

nsfyn55
nsfyn55

Reputation: 15363

You need the wrapper tag. It is what defines the elements as a grouped sequence and not just a bunch of arbitrary elements.

Upvotes: 0

Related Questions