如何将带有属性的Java枚举外部化为XML

时间:2014-09-24 05:16:47

标签: java xml enums jaxb xsd

我有一个Java Enum,如下所示

    public enum TestEnum{
{
     A("a","b","c"),
     B("a1","b1","c1"),
     C("a2","b2","c2");

    TestEnum(String a,String b,String c){
}

private String a;
private String b;
private String c;
}

我想将此配置外部化为XML文件,但XSD似乎不支持Enum Element类型的属性。有没有办法解决这个问题或替代它。

1 个答案:

答案 0 :(得分:0)

你可以做这样的事情(即使对于枚举,这看起来太冗长了)

@XmlJavaTypeAdapter(CountXmlAdapter.class)
public enum Count {

    ONE(1, "one"),
    TWO(2, "two"),
    THREE(3, "three");
    private final int index;
    private final String name;

    private Count(int index, String name) {
        this.index = index;
        this.name = name;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    public static class CountWrapper {

        private int index;
        private String name;

        public CountWrapper() {
        }

        public CountWrapper(int index, String name) {
            this.index = index;
            this.name = name;
        }

    }

    public static class CountXmlAdapter extends XmlAdapter<CountWrapper, Count> {

        @Override
        public Count unmarshal(CountWrapper v) throws Exception {
            return v != null ? Count.valueOf(v.name.toUpperCase()) : null;
        }

        @Override
        public CountWrapper marshal(Count v) throws Exception {
            return v != null ? new CountWrapper(v.index, v.name) : null;
        }

    }
}