簡體   English   中英

為什么以及何時在 JAXB 中需要 JAXBElement?

[英]Why and when JAXBElement is required in JAXB?

我只是在學習 JAXB(用於 XML 綁定的 Java 架構)。 通過閱讀一些來源,我想到了一個關於JAXBElement疑問。

Oracle 文檔說:

When XML element information can not be inferred by the derived Java representation of the XML content, a JAXBElement object is provided. This object has methods for getting and setting the object name and object value. 鏈接在這里

當Schema定義的數據類型和Java數據類型之間沒有直接映射時,是否意味着需要使用JAXBElement

此外,在下面列出的代碼示例之一中。 我從這里遵循:

 ObjectFactory factory = new ObjectFactory();

    UserT user = factory.createUserT();
    user.setUserName("Sanaulla");
    ItemT item = factory.createItemT();
    item.setItemName("Seagate External HDD");
    item.setPurchasedOn("August 24, 2010");
    item.setAmount(new BigDecimal("6776.5"));

    ItemListT itemList = factory.createItemListT();
    itemList.getItem().add(item);

    ExpenseT expense = factory.createExpenseT();// we get expense object here
    expense.setUser(user);
    expense.setItems(itemList);

    JAXBContext context = JAXBContext.newInstance("generated");
    JAXBElement<ExpenseT> element = factory.createExpenseReport(expense);//why is this required
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty("jaxb.formatted.output",Boolean.TRUE);
    marshaller.marshal(element,System.out);

使用ExpenseT expense = factory.createExpenseT(); 我們能夠獲得ExpenseT對象。

再次在代碼中,如果我們看到,我們創建

JAXBElement<ExpenseT> element = factory.createExpenseReport(expense);
根據此來源,它expense對象的包裝器。
另一方面,我們不為使用檢索的對象創建包裝器
UserT user = factory.createUserT();

所以我的問題是:

  1. 圍繞expenseJAXBElement包裝器需要什么?
  2. 何時使用JAXBElement

有幾個用例需要JAXBElement

  1. 一個元素既是nillable="true"又是minOccurs="0" 在這種情況下,映射字段/屬性上的null是什么意思? 當屬性為JAXBElement ,空值表示該元素不存在,而包裝為 null 的JAXBElement表示帶有xsi:nil="true"的 XML 元素。
  2. 有 2 個具有相同命名復雜類型的全局元素。 由於 JAXB 類對應於復雜類型,因此需要一種方法來捕獲遇到的根元素。 有關更多詳細信息,請參閱我寫的這篇文章
  3. 有一個選擇結構,其中可以出現foobar元素,並且它們是相同的類型。 這里需要一個JAXBElement ,因為僅僅遇到一個String值不足以指示應該編組哪個元素。
  4. 在包含屬性的文檔中遇到帶有xsi:nil的元素。 在此示例中,與該元素對應的對象仍然可以解組以保存屬性值,但 JAXBElement 仍然可以指示該元素為空。

JAXBElement 用於在對象模型中沒有足夠信息的用例中保留元素名稱/命名空間。 它通常與替換組一起使用。

如果沒有任何 JAXB 元數據,結果將被包裝在 JAXBElement 中。 您可以使用 @XmlRootElement 注釋消除根級別 JAXBElement。

如果您使用來自外部源的 xsd 文件並且在生成的類上沒有可用的 XmlRootElement 注釋,則在編組過程中使用 JAXBElement 真的會派上用場,因為您可以使用 JAXBElement 包裝器將 xml 解組為對象。 你會看到在這種情況下指定類本身不起作用......

這將起作用:

JAXBElement<Object> je = (JAXBElement<Object>) unmarshaller.unmarshal(objectXML);
Object = je.getValue();

這將拋出一個 JAXBException:

Object obj = (Object) unmarshaller.unmarshal(objectXML);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM