[英]Writing stax XML to String
我正在使用stax来创建我的Web应用程序所需的XML文档。 目前我在这样的文件中创建我的XML:
XMLOutputFactory factory = XMLOutputFactory.newInstance();
String output=null;
try
{
XMLStreamWriter writer = factory.createXMLStreamWriter(
new FileWriter("C:\\Junk\\xmlDoc.xml"));
writer.writeStartDocument();
writer.writeStartElement("TagName1");
writer.writeAttribute("AAA", "BBB");
writer.writeEndElement();
writer.writeEndDocument();
writer.flush();
writer.close();
}
catch (XMLStreamException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
但是xml文件不是我想要的,我需要在String
创建我的XML。 不幸的是我无法弄清楚我需要哪个OutputStream
对象而不是FileWriter
你需要一个java.io.StringWriter
:
与FileWriter
一样,它派生自Writer
,可以传递给factory.createXMLStreamWriter
。 完成后,您可以将书面内容转换为字符串。
StringWriter stringOut = new StringWriter();
XMLStreamWriter writer = factory.createXMLStreamWriter(stringOut);
... // write XML
String output = stringOut.toString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.