2012-08-02 118 views
2

我想使用参数从enum Type中创建一个xml。将Java ENUM转换为XML

如:

@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 2012-08-02 20:21:25

回答

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

}