簡體   English   中英

通用JAXB到同一XML包裹的不同XML

[英]Generic JAXB to different XMLs wrapped by same XML

我有一個XML,其中的一些公共部分包裝可以以任何方式更改的特定部分。

例如,我將必須管理以下兩個XML(簡化):

...
<xml>
<common>
    <data1>1</data1>
    <data2>2</data2>
</common>
<specific>
    <specific-info>
        <color>blue</color>
    </specific-info>
</specific>
</xml>
...

還有這個:

...
<xml>
<common>
    <data1>33</data1>
    <data2>42</data2>
</common>
<specific>
    <another-info>
        <age>42</age>
    </another-info>
</specific>
</xml>
...

因此,我已經使用JAXB繼承了此代碼(簡體),該代碼有效:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {})
@XmlRootElement(name = "xml")
public class Specific{
  @XmlElement(name = "common", required = true)
  protected CommonData common;
  @XmlElement(name = "specific")
  protected SpecificInfo specificInfo;
  @XmlElement(name = "specific")
  protected AnotherInfo anotherInfo;

    // getters and setters
}

問題是,當一種新的信息到達時,我必須添加具有相同名稱的新XMLElement,我認為它聞起來...而且它們是每個方法的獲取者。

還有另一種負擔得起的方式嗎? 這是用JAXB解開包裝的XML的標准方法嗎?

如果我了解您的需求,您希望能夠將其他元素的內容放入<specific/>嗎?

因此,也許您可​​以根據要捕獲的結構來查看@XmlAnyElement

您可能對旨在保留對specificInfo和anotherInfo的處理的寬松屬性感興趣

@XmlAnyElement(lax="true")
public Object[] others;

以@fisc展示給我的方式,我以他的方式在我的bean @XmlAnyElement中使用了它:

@XmlAnyElement(lax=true)
public Object[] others;

它將xml的特定部分作為xml DOM對象獲取,還使用此方法獲取實際對象,而不是xml中存在的DOM表示形式:

@SuppressWarnings("unchecked")
    public <T> T getOthersParsedAs(Class<T> clazz) throws JAXBException{
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        T res = (T) unmarshaller.unmarshal((Node)others[0]);    
        if (res instanceof JAXBElement){
            res = (T)JAXBIntrospector.getValue(res); 
        }
        return res;
    }

這樣,我無法獲得它們:

Specific spec = ...
SpecificInfo info = spec.getOthersParsedAs(SpecificInfo.class);

要么:

AnotherInfo info = spec.getOthersParsedAs(AnotherInfo .class);

更新

我已經完成了一種方法,可以在該節點的xml中插入任何對象(難看,但是在同一方法中顯示了所有代碼):

public <T> void setOthersInXML(T data) throws JAXBException, ParserConfigurationException{
        JAXBContext context = JAXBContext.newInstance(data.getClass());
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db= dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(data, document);
        others = new Object[]{document.getDocumentElement()};
    }

和像二傳手一樣使用。

再次編輯

因為我發現了一個問題:如果該類的定義不正確,則XMLRootElement getOthersParsedAs將返回一個JAXBElement對象,這可能會出現問題,因此我將檢查添加到了方法中

暫無
暫無

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

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