【发布时间】:2011-08-27 06:52:24
【问题描述】:
是否可以将 javax.xml.bind.annotation.XmlType 转换为 XML 的字符串表示形式?
例子:
以下类 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 的字符串表示,以便我可以将其记录到文件中:
<Req>
<MyDetails>
...
</MyDetails>
<CustomerDetails>
...
</CustomerDetails>
</Req>
当我尝试使用 JAXB 和 Marshall 转换为 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 注释。有什么办法吗?
【问题讨论】: