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避免使用复杂的名字。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容