将Java ENUM转换为XML

3

我希望能够从带有参数的枚举类型中创建一个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
你尝试过使用XmlAdapter吗? - SHiRKiT
1个回答

0

你可能需要这个

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

输出 <root><category description="鸡蛋">食品</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;
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接