public static String toXml() {
KtpMessage ktpMessage =new KtpMessage();
ktpMessage.setdetails("test");
XStream xstream = new XStream(new StaxDriver());
String objectXml = xstream.toXML(ktpMessage);
return objectXml;
结果是:
<?xml version='1.0' encoding='utf-8'?><myclasses.Message><details>test</details></myclasses.Message>
我的问题:
我想生成“objectXml”但没有<?xml version='1.0' encoding='utf-8'?>
我怎么能这样做?
我希望得到这样的结果:
<myclasses.Message><details>test</details></myclasses.Message>
感谢您的帮助
答案 0 :(得分:1)
如果您创建自己的StaxWriter,则可以使用构造函数来告诉它不要编写startDocument
StAX事件(这是创建XML声明的事件)。这样的事情(省略了异常处理):
StaxDriver drv = new StaxDriver();
XStream xstream = new XStream(drv);
StringWriter strWriter = new StringWriter();
StaxWriter sw = new StaxWriter(drv.getQnameMap(),
drv.getOutputFactory().createXMLStreamWriter(strWriter),
false, // don't do startDocument
true); // do repair namespaces
xstream.marshal(ktpMessage, sw);
sw.close();
String objectXml = strWriter.toString();