一般來說,一個Order不止含有一個Product,就需要使用到 List 了。
@Test
public void test2() throws JAXBException {
Product p1 = new Product();
p1.setId("11021");
p1.setName("Apple");
Product p2 = new Product();
p2.setId("11022");
p2.setName("Banana");
List<Product> list = Arrays.asList(p1,p2);
Order2 order = new Order2();
order.setId("1102");
order.setPrice(45.67);
order.setProduct(list);
JAXBContext context = JAXBContext.newInstance(Order2.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(order, System.out);
}
對象 Order2 的第三個字段是 List 類型。Product和上例中的一樣。
@XmlRootElement(name = "Order")
public class Order2 {
private String id;
private Double price;
private List<Product> product;
//setters, getters
}
生成的XML中 product 重復出現(xiàn)多次。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Order>
<id>1102</id>
<price>45.67</price>
<product id="11021">
<name>Apple</name>
</product>
<product id="11022">
<name>Banana</name>
</product>
</Order>
上例中的Product是散落著的數(shù)據(jù),有時候可能需要將其包裹起來,這時只需要改動 Order 對象。
@XmlRootElement(name = "Order")
@XmlAccessorType(XmlAccessType.FIELD)
public class Order3 {
private String id;
private Double price;
@XmlElementWrapper(name = "Products")
private List<Product> product;
編組過程和上例中的相同,生成的XML包含了一個 Products 包裹著所有的 Product
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Order>
<id>1102</id>
<price>45.67</price>
<Products>
<product id="11021">
<name>Apple</name>
</product>
<product id="11022">
<name>Banana</name>
</product>
</Products>
</Order>
更多建議: