JAXB element of type enum

前端 未结 2 1709
被撕碎了的回忆
被撕碎了的回忆 2021-02-03 22:16

So I know how to create an enum type but when I set an element type to it the element field will just be of type string and not of type enum. How do I create an enum in my schem

相关标签:
2条回答
  • 2021-02-03 22:54

    You could form your XML schema as follows:

    <?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>
    

    Will cause the following Enum to be generated:

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

    And the following class that leverages that 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;
        }
    
    }
    

    For More Information

    • http://blog.bdoughan.com/2011/08/jaxb-and-enums.html
    0 讨论(0)
  • 2021-02-03 23:14

    See jaxb:globalBindings/@typeSafeEnumBase here.

    0 讨论(0)
提交回复
热议问题