JAXB @XmlElements使minOccurs = 1

时间:2011-05-16 20:05:09

标签: java xml xsd jaxb

所以我想要一个用@XmlElements注释的列表,如下所示

@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;
}

我想知道是否有办法强制列表包含至少1个元素,因为现在,xsd看起来像

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

2 个答案:

答案 0 :(得分:13)

我建议检查:

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

答案 1 :(得分:3)

假设Apple,Orange和Mango是Fruit的子类,您可能希望使用entries注释@XmlElementRef属性,该属性对应于XML架构中的替换组,而不是@XmlElements对应于选择的概念。

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

这假设Apple,Orange和Mango类扩展了Fruit类,并使用@XmlRootElement注释

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

了解更多信息