枚举类型的JAXB元素

时间:2011-04-27 15:51:43

标签: enums types schema jaxb element

所以我知道如何创建枚举类型,但是当我为它设置元素类型时,元素字段将只是字符串类型而不是类型枚举。如何在我的模式中创建枚举并让JAXB将其生成为java枚举类型?

这就是我在进行枚举类型和元素创建的方式:

<xsd:simpleType name="myEnum">
    <xsd:restriction base="xsd:string">
        <xsd:enumeration value="MY_ENUM_1"/>
        <xsd:enumeration value="MY_ENUM_2"/>
    </xsd:restriction>
</xsd:simpleType>

<xsd:element name="myEnumElement" type="ns1:myEnum"/>

2 个答案:

答案 0 :(得分:44)

您可以按如下方式构建XML架构:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="http://www.example.com" xmlns="http://www.example.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:simpleType name="myEnum">
        <xsd:restriction base="xsd:string">
            <xsd:enumeration value="MY_ENUM_1"/>
            <xsd:enumeration value="MY_ENUM_2"/>
        </xsd:restriction>
    </xsd:simpleType>
    <xsd:element name="root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="local" type="myEnum"/>
                <xsd:element name="ref" type="myEnum"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

将导致生成以下枚举:

package com.example;

import javax.xml.bind.annotation.*;

@XmlType(name = "myEnum")
@XmlEnum
public enum MyEnum {

    MY_ENUM_1,
    MY_ENUM_2;

    public String value() {
        return name();
    }

    public static MyEnum fromValue(String v) {
        return valueOf(v);
    }

}

以下类利用了Enum:

package com.example;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "local",
    "ref"
})
@XmlRootElement(name = "root")
public class Root {

    @XmlElement(required = true)
    protected MyEnum local;
    @XmlElement(required = true)
    protected MyEnum ref;

    public MyEnum getLocal() {
        return local;
    }

    public void setLocal(MyEnum value) {
        this.local = value;
    }

    public MyEnum getRef() {
        return ref;
    }

    public void setRef(MyEnum value) {
        this.ref = value;
    }

}

了解更多信息

答案 1 :(得分:3)

请参阅jaxb:globalBindings/@typeSafeEnumBase here