原文地址:[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避免使用復雜的名字。