---
title: "Writing xml string with StAX"  
description: "Writing xml string with StAX"  
author: "Anonymous User"  
published: 2015-12-11  
updated: 2015-12-11  
canonical: https://www.mindstick.com/forum/33719/writing-xml-string-with-stax  
category: "java"  
tags: ["xml", "java", "string"]  
reading_time: 2 minutes  

---

# 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](https://www.mindstick.com/forum/161912/explain-the-python-strings).\
How do I get around this limitation considering I have to write a [large](https://www.mindstick.com/interview/34471/what-is-a-large-language-model-llm) [xml file](https://www.mindstick.com/forum/360/how-to-read-xml-file-in-php) (> 100 MB).\
I have arbitrary xml strings like this, sometimes with a fairly [complex](https://yourviews.mindstick.com/audio/1142/understanding-the-complex-factors-influencing-mental-health) [structure](https://www.mindstick.com/articles/23258/choose-your-business-structure-wisely), that need to be added [together](https://yourviews.mindstick.com/view/80819/live-in-relationship-protecting-the-right-to-live-together) with some other details to [form](https://www.mindstick.com/forum/6/multi-form-mfc-application) 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>
```

## Replies

### Reply by Anonymous User

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](https://www.mindstick.com/blog/203/working-with-xml-data-in-sql-server) 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.


---

Original Source: https://www.mindstick.com/forum/33719/writing-xml-string-with-stax

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
