将Java ENUM转换为XML

时间:2012-08-02 20:02:10

标签: java xml jaxb

我想从enum Type中创建带参数的xml。

e.g:

@XmlRootElement(name="category")  
@XmlAccessorType(XmlAccessType.NONE)  
public enum category{  
     FOOD(2, "egg"),  

     private final double value;  

     @XmlElement  
     private final String description;  


    private Category(double value, String name){  

       this.value = value;  
       this.description = name;  
    }  
}    

我想生成的XML就像这样

 <category>  
 FOOD
 <description>Egg</description>  
 </category> 

但是,这就是我所拥有的:

<category>FOOD</category>  

javax.xml.bind.annotation中的任何注释都可以这样做吗?

抱歉我的英文不好

1 个答案:

答案 0 :(得分:0)

你可能想要这个

marshaller.marshal(new Root(), writer);

输出<root><category description="egg">FOOD</category></root>

因为@XmlValue和@XmlElement不允许属于同一个类 我将其更改为属性

@XmlJavaTypeAdapter(CategoryAdapter.class)
enum Category {
    FOOD(2D, "egg");

    private double value;

    @XmlAttribute
    String description;

    Category(double value, String name) {
        this.value = value;
        this.description = name;
    }
}

@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
class Root {
    @XmlElementRef
    Category c = Category.FOOD;
}

@XmlRootElement(name = "category")
@XmlAccessorType(XmlAccessType.NONE)
class PrintableCategory {

    @XmlAttribute
    //@XmlElement
    String description;

    @XmlValue
    String c;
}

class CategoryAdapter extends XmlAdapter<PrintableCategory, Category> {

    @Override
    public Category unmarshal(PrintableCategory v) throws Exception {
        return Category.valueOf(v.c);
    }

    @Override
    public PrintableCategory marshal(Category v) throws Exception {
        PrintableCategory printableCategory = new PrintableCategory();
        printableCategory.description = v.description;
        printableCategory.c = v.name();
        return printableCategory;
    }

}