JAXB的@XmlElement注解

原文地址:[https://jaxb.java.net/tutorial/section_6_2_7_1-Annotations-for-Fields.html#The Annotation XmlElement](https://jaxb.java.net/tutorial/section_6_2_7_1-Annotations-for-Fields.html#The Annotation XmlElement)

對一個field來說,最基本的注解就是@XmlElement。它表示這個field將在XML中被轉成一個element。它允許你定義XML的name,namespace,還有它是否是可選的(optional)或者是可為空的(nillable),默認值,Java類。這里是兩個被注解的field,下面是對應的schema片段:

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

如果一個field有一些collection類型,那么將不得不將超過一個@XmlElement的注解關聯這個field。這需要這些注解被組裝到一個@XmlElements注解,而它只是作為一個容器。在下面這個class定義中,它的entryOrChoiceOrCascade field是一個collection,其中包含了三個不同類的對象。

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

你應該為list element避免使用復雜的名字。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容