首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JAXB 生成 XML 屬性:@XmlAttribute 正確用法與內部類結構

     編輯:程式設計疑難解答

目標 XML 結構

<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 屬性。

實體類設計要點

  1. @XmlAttribute 標註在 **field 或 getter** 上,映射為 XML 屬性。
  2. 屬性對應的 Java 欄位**不應**出現在 @XmlType(propOrder) 中(propOrder 僅控制元素順序)。
  3. 巢狀結構(如 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,屬性位置、命名正確即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved