[英]How to get String representation of XmlType?
是否可以將javax.xml.bind.annotation.XmlType轉換為XML的String表示形式?
例:
以下類Req來自第三方庫,因此我無法覆蓋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的String表示,以便我可以將其記錄到文件中:
<Req>
<MyDetails>
...
</MyDetails>
<CustomerDetails>
...
</CustomerDetails>
</Req>
當我嘗試使用JAXB和Marshall轉換為XML String時:
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注釋。 有什么方法嗎?
您可以使用JAXB並將其編組為xml字符串
JAXBContext context = JAXBContext.newInstance(Req.class);
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.marshal(instanceOfReq, sw);
String xmlString = sw.toString();
添加到Bala R指示的內容,如果您的JAXB元素沒有@xmlrootelement
,則可以執行此@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();
這也在這里說。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.