Rox Rox - 2 months ago 8
Java Question

JAXB: code generation of elements with maxOccurs property set in the xsd file don´t get a set-method in the java class

I have a xsd file called

Person
with some elements. Some of the elements have both properties
minOccurs
and
maxOccurs
set. Two lines in the xsd file could look like this.

<xsd:element name="NameOfElement" minOccurs="0" maxOccurs="unbounded">
<xsd:element name="NameOfAnotherElement" minOccurs="0">


In NetBeans I want to generate Java classes of this xsd file using JAXB.
All elements that just have the
minOccurs
property get both a set and a get method in the generated
Person
java file, but the elements that have both
minOccurs
and
maxOccurs
properties set in the xsd file become a List. So the above xsd lines become this after the generation:

@XmlElement(name = NameOfElement)
protected List<Person.NameOfElement> nameOfElement;
@XmlElement(name = NameOfAnotherElement)
protected Person.NameOfAnotherElement nameOfAnotherElement;


The strange thing is that the variable
nameOfAnotherElement
gets both a set and a get method in the
Person
java class and
nameOfElement
only gets a get method.

Why donĀ“t elements that become a
List<>
in the Java code get a set method (those elements that have both properties
minOccurs
and
maxOccurs
set in the xsd)?

So my problem is that I cannot set the NameOfElement to a Person object because it misses a set method, but it contains a get method! Why is that so?

Answer

If you have maxOccurs set to != 1, it can contain multiple instances of that element, so it becomes a list.

You should use the get method, and then add elements to that list. Something like this:

List<Person.NameOfElement> myList = doc.getNameOfElement();
myList.add(obj);

Edit: if you already have a list you want to use you can do the follwing:

doc.getNameOfElement().addAll(myList);