2011-05-17 72 views
13

是否可以將javax.xml.bind.annotation.XmlType轉換爲XML的字符串表示形式?如何獲取XmlType的字符串表示形式?

實施例:

下面的類所需物品是從第三方庫,所以我不能重寫toString()方法。

@javax.xml.bind.annotation.XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD) 
@javax.xml.bind.annotation.XmlType(name = "req", propOrder = {"myDetails", "customerDetails"}) 
public class Req { 
... 
} 

在我的應用我想簡單地獲取XML的字符串表示,這樣我可以把它記錄到一個文件:

<Req> 
    <MyDetails> 
    ... 
    </MyDetails> 
    <CustomerDetails> 
    ... 
    </CustomerDetails> 
</Req> 

當我嘗試使用JAXB和馬歇爾轉換爲XML字符串:

JAXBContext context = JAXBContext.newInstance(Req.class); 
Marshaller marshaller = context.createMarshaller(); 
StringWriter sw = new StringWriter(); 
marshaller.marshal(instanceOfReq, sw); 
String xmlString = sw.toString(); 

我得到以下異常:

javax.xml.bind.MarshalException 
    - with linked exception: 
    [com.sun.istack.SAXException2: unable to marshal type "mypackage.Req" as an element because it is missing an @XmlRootElement annotation] 

我查看了第三方庫中的其他類,並且它們都沒有使用@XmlRootElement註釋。任何方式在這個?

回答

19

您可以使用JAXB和編組到XML字符串

JAXBContext context = JAXBContext.newInstance(Req.class); 
Marshaller marshaller = context.createMarshaller(); 
StringWriter sw = new StringWriter(); 
marshaller.marshal(instanceOfReq, sw); 

String xmlString = sw.toString(); 
+3

OP的警告:'JAXBContext's創建成本很高(很慢)。創建並重用單個實例。 – 2011-05-17 14:14:19

+1

嘗試使用JAXB和Marshall,但獲取上述帖子中描述的MarshalException。 – ryan 2011-05-17 14:53:12

+0

並且您無法更改類Req以添加XmlRoot批註? – 2011-05-17 14:54:27

3

Addding什麼巴拉R所示,你可以做到這一點,如果你的JAXB元素不具備的@xmlrootelement

JAXBContext context = JAXBContext.newInstance(YourClass.class); 
      Marshaller marshaller = context.createMarshaller(); 
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 
      StringWriter sw = new StringWriter(); 
      JAXBElement jx = new JAXBElement(new QName("YourRootElement"), YourClass.class, input); 
      marshaller.marshal(jx, sw); 
      String xmlString = sw.toString(); 

這也被稱爲here

相關問題