2016-08-22 82 views
0

假设我正在尝试从对象中创建XML文档。这可能在单个Food类上使用JAXB注释,还是需要为Cost和Flavor创建内部类?序列化多层XML元素

我知道我可以使用@XmlElement或@XmlAttribute来设置我的根元素的直接子元素。但是,我不确定是否/如何创建<cost><Flavor>标签,如我在此处展示的那样。

<Food> 
    <cost amt=13.5 unit=USD/> 
    <Flavor spicy=5>It tastes good</Flavor> 
</Food> 


@XmlRootElement("Food") 
public class Food { 

    private float amount; 
    private String units; 
    private String flavorType; 
    private STring flavorDescription; 
} 
+0

我认为你需要内部类两种'cost'和'flavor' –

回答

1

添加一个新的Java类成本

public class Cost 
{ 
    @XmlAttribute 
    double amt; 
    @XmlAttribute 
    String unit; 
} 

而且exdend类食品

@XmlRootElement 
public class Food { 

    private float amount; 
    private String units; 
    private String flavorType; 
    private String flavorDescription; 

    private Cost cost; 
    ... 
0

你也可以使用类似这样的香精类

公共课风味{

私人长辣;
private String shortDesc;

@XmlValue
公共字符串getShortDesc(){
返回shortDesc;
}
public void setShortDesc(String shortDesc){
this.shortDesc = shortDesc;
}
@XmlAttribute
众长getSpicy(){
回报辛辣;
}
public void setSpicy(long spicy){
this.spicy = spicy;
}

}