I am using stax to create XML document that I need for my web app. Currently I am creating my XML in a file like this:
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();
}
But an xml file is not what I want, I need to create my XML in a String
.
Unfortunately I can't figure out which OutputStream
object I need instead of the FileWriter
You need a java.io.StringWriter
:
Like FileWriter
it derives from Writer
and can be passed to factory.createXMLStreamWriter
. And once your are done you can turn the written content into a string.
StringWriter stringOut = new StringWriter();
XMLStreamWriter writer = factory.createXMLStreamWriter(stringOut);
... // write XML
String output = stringOut.toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With