Order對象中包含Product對象,這在項(xiàng)目中是常見情形。
public void test1() throws JAXBException {
Product p = new Product();
p.setId("1100");
p.setName("Apple");
Order order = new Order();
order.setId("1101");
order.setPrice(23.45);
order.setProduct(p);
JAXBContext context = JAXBContext.newInstance(Order.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(order, System.out);
}
Order對象的第三個屬性是個復(fù)雜的數(shù)據(jù)類型。
@XmlRootElement(name = "Order")
public class Order {
private String id;
private Double price;
private Product product;
//setters, getters
}
被嵌套的 Product 不需要使用 @XmlRootElement
注解,使用注解 @XmlAccessorType
是因?yàn)槲蚁矚g將注解標(biāo)注在字段Filed
上面。
@XmlAccessorType(XmlAccessType.FIELD)
public class Product {
@XmlAttribute
private String id;
private String name;
//setters, getters
}
生成的XML含有兩個層級。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Order>
<id>1101</id>
<price>23.45</price>
<product id="1100">
<name>Apple</name>
</product>
</Order>
更多建議: