是否可以将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