是否可以将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 {
...
}
Run Code Online (Sandbox Code Playgroud)
在我的应用程序中,我想简单地获取XML的String表示,以便我可以将其记录到文件中:
<Req>
<MyDetails>
...
</MyDetails>
<CustomerDetails>
...
</CustomerDetails>
</Req>
Run Code Online (Sandbox Code Playgroud)
当我尝试使用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();
Run Code Online (Sandbox Code Playgroud)
我得到以下异常:
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]
Run Code Online (Sandbox Code Playgroud)
我查看了第三方库中的其他类,但没有一个使用@XmlRootElement注释.有什么方法吗?
Bal*_*a R 22
您可以使用JAXB并将其编组为xml字符串
JAXBContext context = JAXBContext.newInstance(Req.class);
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.marshal(instanceOfReq, sw);
String xmlString = sw.toString();
Run Code Online (Sandbox Code Playgroud)
添加到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();
Run Code Online (Sandbox Code Playgroud)
这也在这里说.
| 归档时间: |
|
| 查看次数: |
15189 次 |
| 最近记录: |