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)

對一個(gè)field來說,最基本的注解就是@XmlElement。它表示這個(gè)field將在XML中被轉(zhuǎn)成一個(gè)element。它允許你定義XML的name,namespace,還有它是否是可選的(optional)或者是可為空的(nillable),默認(rèn)值,Java類。這里是兩個(gè)被注解的field,下面是對應(yīng)的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>

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

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

你應(yīng)該為list element避免使用復(fù)雜的名字。

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

推薦閱讀更多精彩內(nèi)容