Home > DeveloperSection > Forums > Writing xml string with StAX
jimmy Smith
jimmy Smith

Total Post:3

Posted on    December-11-2015 1:08 AM

 Java XML  Java  String 

 1 Reply(s)
 552  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

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    December-11-2015 1:19 AM

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.

Don't want to miss updates? Please click the below button!

Follow MindStick