Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB @XmlElements to have minOccurs = 1

Tags:

java

xml

jaxb

xsd

So I want to have a list to be annotated with @XmlElements like the following

@XmlElements(
        {
            @XmlElement(name = "Apple", type = Apple.class),
            @XmlElement(name = "Orange", type = Orange.class),
            @XmlElement(name = "Mango", type = Mango.class)
        }
)
public List<Fruit> getEntries() {
        return fruitList;
}

I am wondering whether there is a way to enforce the list to contain at least 1 element, because right now, the xsd looks like

<xs:complexType name="fruitList">
    <xs:sequence>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Apple" type="tns:apple"/>
        <xs:element name="Orange" type="tns:orange"/>
        <xs:element name="Mango" type="tns:mango"/>
      </xs:choice>
    </xs:sequence>
  </xs:complexType>
like image 425
denniss Avatar asked May 16 '11 20:05

denniss


2 Answers

I suggest to check:

@XmlElements(
    {
        @XmlElement(name = "Apple", type = Apple.class, required = true),
        @XmlElement(name = "Orange", type = Orange.class, required = true),
        @XmlElement(name = "Mango", type = Mango.class, required = true)
    }
)
like image 90
jrq85 Avatar answered Oct 18 '22 20:10

jrq85


Assuming that Apple, Orange, and Mango are subclasses of Fruit you may want to annotate the entries property with @XmlElementRef which corresponds to substitution groups in XML schema, rather than @XmlElements which corresponds to the concept of choice.

@XmlElementRef
public List<Fruit> getEntries() {
        return fruitList;
}

This assumes that the Apple, Orange, and Mango classes extend the Fruit class, and are annotated with @XmlRootElement

@XmlRootElement
public class Apple extends Fruit {
   ...
}

For More Information

  • http://bdoughan.blogspot.com/2010/11/jaxb-and-inheritance-using-substitution.html
  • http://bdoughan.blogspot.com/2010/10/jaxb-and-xsd-choice-xmlelements.html
like image 3
bdoughan Avatar answered Oct 18 '22 19:10

bdoughan