2012-08-02 158 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; 
    } 

}