3

我想从带有参数的枚举类型中创建一个 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 中的任何注释都可以做到这一点吗?

对不起,我的英语不好

4

1 回答 1

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

}
于 2012-10-08T17:28:41.017 回答