Writing xml string with StAX

Total Post:3

XML  Java  String 
 898  View(s)
Rate this:
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.

<name>Strawberry Belgian Waffles</name>
Light Belgian waffles covered with strawberries and whipped cream
  1. Post:397

    Re: Writing xml string with StAX

    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);
    // 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.