2012-08-06 208 views
9

我不確定下列問題是否可以用jaxb,但我會問。Jaxb可以元素沒有根元素的元素嗎?

在某個項目中,我們使用具有已定義模式的jaxb來創建xml文件的下一個結構。

<aaa> 
    <bbb> 
     more inner children here 
    </bbb> 
    <bbb> 
     more inner children here 
    </bbb> 
</aaa> 

我們還利用JAXB的自動類發生它創建的類:AAA和bbb,,其中aaa被作爲@XmlRootElement生成。

我們現在想在新項目中使用相同的模式,這也將與以前的項目兼容。 我想要做的是使用相同的jaxb生成的類,而不對模式進行任何更改,以便僅將單個bbb對象編組爲xml。作爲編組破口大罵,我沒有@XmlRootElement定義做

<bbb> 
    <inner child1/> 
    <inner child2/> 
    ... 
</bbb> 

我目前不能夠這樣做:

JAXBContext jc = JAXBContext.newInstance("generated"); 
Marshaller marshaller = jc.createMarshaller(); 
marshaller.marshal(bbb, writer); 

所以我們會得到下一個結果。

我們實際上試圖避免將模式分解爲2個模式的情況,其中只有一個是bbb,另一個是aaa導入bbb。

在此先感謝!

+3

我能找到這個職位的解決方案: [使用JAXB零散編組] [1] [1]:http://stackoverflow.com/questions/9295385/jaxb-fragmented-marshalling?lq=1 – 2012-08-06 07:43:53

回答

11

我也許晚了3年,但你有沒有嘗試過這樣的事情:

public static String marshal(Bbb bbb) throws JAXBException { 
    StringWriter stringWriter = new StringWriter(); 

    JAXBContext jaxbContext = JAXBContext.newInstance(Bbb.class); 
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); 

    // format the XML output 
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 

    QName qName = new QName("com.yourModel.bbb", "bbb"); 
    JAXBElement<Bbb> root = new JAXBElement<Bbb>(qName, Bbb.class, bbb); 

    jaxbMarshaller.marshal(root, stringWriter); 

    String result = stringWriter.toString(); 
    LOGGER.info(result); 
    return result; 
} 

這裏是當我有沒有rootElement的元帥/解組我使用的文章: http://www.source4code.info/2013/07/jaxb-marshal-unmarshal-with-missing.html

它對我來說工作得很好。我正在爲其他失去靈魂尋找答案的人寫回應。

所有最好的:)

-1

我也許後期用5年時間:)但是你有沒有嘗試過這樣的事情:

StringWriter stringWriter = new StringWriter(); 
JAXB.marshal(bbb, stringWriter); 
String bbbString = stringWriter.toString();