简体   繁体   中英

JAXB @XmlElements to have minOccurs = 1

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>

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)
    }
)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM