Search code examples
javajaxbstax

Writing xml string with StAX


Is it possible to write an xml chunk directly using StAX? I know I can use an XMLStreamWriter with writeStartElement, writeCharacters and writeEndElement but there is no flexibility for xml strings.

How do I get around this limitation considering I have to write a large xml file (> 100 MB).

I have arbitrary xml strings like this, sometimes with a fairly complex structure, that need to be added together with some other details to form the final xml file. This is just an example not the actual xml string.

<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>
Light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>

Solution

  • While there is a method writeCharacters() on XMLStreamWriter this doesn't do what you want. It's after all escaping '<', '>', '&'

    since you already have the XML String in memory you might resort to a hack.

    Whenever you need to write raw XML keep a reference to the underlying writer and do the following:

    // somewhere before:
    Writer underlyingWriter = /* get the underlying writer from somewhere */;
    XMLStreamWriter xmlStreamWriter = factory.createXmlStreamWriter(underlyingWriter);
    
    xmlStreamWriter.flush();
    underlyingWriter.write(rawXML);
    underlyingWriter.flush();
    // carry on using the XMLStreamWriter
    

    You need to flush the xmlStreamWriter before using the underlying writer to ensure correct order of elements. Additionally you should flush the underlyingWriter for the exact same reason.