<menu>
<food category="starter" type="veg">
<name>Salad</name>
<price>5.99</price>
<description type="short">Fresh garden salad</description>
<calories>120</calories>
</food>
</menu>
重點:food 元素帶 category、type 兩屬性;description 也帶 type 屬性。
@XmlAttribute 標註在 **field 或 getter** 上,映射為 XML 屬性。@XmlType(propOrder) 中(propOrder 僅控制元素順序)。description)需建立獨立內部類,同樣用 @XmlAttribute。@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "name", "price", "description", "calories" }) // 不含 type、category
@XmlRootElement(name = "food")
public static class Food {
@XmlElement(required = true) protected String name;
@XmlElement(defaultValue = "1") protected float price;
@XmlElement(required = true, defaultValue = "") protected String description;
protected int calories;
@XmlAttribute(name = "category", required = true) protected String category;
@XmlAttribute(name = "type", required = true) protected String type; // 直接屬性
// description 帶屬性,需單獨類
@XmlAccessorType(XmlAccessType.FIELD)
public static class Description {
@XmlAttribute(name = "type", required = true) protected String type;
@XmlValue protected String value; // 元素文本內容
// getter/setter...
}
protected Description description; // 對應 XML 中的 description 元素
// getter/setter...
}
propOrder 中的 "type",否則 JAXB 會嘗試將其作為子元素序列化。Description 類用 @XmlValue 映射元素文本,@XmlAttribute 映射屬性。category、type 非 null,否則 required=true 會拋異常。JAXBContext ctx = JAXBContext.newInstance(Menu.class);
Marshaller m = ctx.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(menuObj, System.out);
輸出對比預期 XML,屬性位置、命名正確即可。