JAXB - Annotations, The Annotation XmlElement

The basic annotation for a field that's intended to be an element is XmlElement. It permits you to define the XML element name, the namespace, whether it is optional or nillable, a default value and the Java class. Here are two annotated fields, and below is the corresponding schema snippet.

@XmlElement(name = "Preamble", required = true)
protected PreambleType preamble;
@XmlElement(name = "Workplace", required = true)
protected List<SysWorkplaceType> workplace;
<xsd:sequence>
    <xsd:element name="Preamble" type="com:PreambleType"/>
    <xsd:element name="Workplace" type="SysWorkplaceType" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>

 

If a field has some collection type, more than one @XmlElement may have to be associated with this field. This requires that these annotations are assembled in a XmlElements (not the plural "s") annotation that merely acts as a container. In the class definition below, the field entryOrChoiceOrCascade is a collection composed from objects of three different classes.

@XmlType(name = "MenuType")
public class MenuType extends ItemType {

    @XmlElements({
        @XmlElement(name = "Item",     type = ItemType.class),
        @XmlElement(name = "CheckBox", type = CheckBoxType.class),
        @XmlElement(name = "Menu",     type = MenuType.class)
    })
    protected List entryList;
}

As a bonus you may avoid the complicated name for the list element that JAXB concocts from the first three possibles.

posted on 2016-05-20 15:28  huey2672  阅读(188)  评论(0编辑  收藏  举报