是否可以将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注释。有什么方法吗?
答案 0 :(得分:21)
您可以使用JAXB并将其编组为xml字符串
JAXBContext context = JAXBContext.newInstance(Req.class);
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.marshal(instanceOfReq, sw);
String xmlString = sw.toString();
答案 1 :(得分:5)
添加到Bala 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。