Search code examples
javaxmljava-iostax

Writing stax XML to String


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


Solution

  • 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();