是否可以將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註釋。任何方式在這個?
OP的警告:'JAXBContext's創建成本很高(很慢)。創建並重用單個實例。 – 2011-05-17 14:14:19
嘗試使用JAXB和Marshall,但獲取上述帖子中描述的MarshalException。 – ryan 2011-05-17 14:53:12
並且您無法更改類Req以添加XmlRoot批註? – 2011-05-17 14:54:27