原文地址:[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ù)雜的名字。