3

我的程序JAVA:

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>

感谢您的帮助

4

1 回答 1

1

如果您创建自己的StaxWriter,则可以使用构造函数告诉它不要编写startDocumentStAX 事件(这是创建 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();
于 2013-04-02T11:30:38.330 回答