Open In App
Related Articles

XMLStreamWriter in Java StAX

Improve Article
Save Article
Like Article

Streaming API for XML added in Java 6 provides a handy interface XMLStreamWriter which is used for writing XML documents. this API does not require building any specific object structure like in DOM and doing any intermediate tasks. It also supports namespaces by default which is very useful in more advanced situations.

Methods that are incorporated in order to create XMLStreamWriter object and write data into it are listed below as follows:

  • writeStartDocument()
  • writeStartElement()
  • writeCharacters()
  • writeEndElement()
  • writeEndDocument()

There are certain limitations been attached with  XMLStreamWriter in java StAX of which primarily are as follows:

  1. It is still possible to create not well-formed XML documents which for example contain more than one root element or miss namespace definition.
  2. XMLStreamWriter does not indent its output so it may be a bit hard to read using a plain text editor. Therefore, for reading, it is suggested to open it in a web browser most of which has a user-friendly interface to view the structure of XML documents.


  1. Create instance of XMLStreamWriter using XMLOutputFactory
  2. Write the header of the XML and proceed to write elements.
  3. After adding elements we can add attributes, character data, or CDATA
  4. Close opened elements
  5. Emptying elements or write comments
  6. Close and finish XML document

Now let us do discuss more how they are written later on implementing the same in our java program.

Step 1: Create instance of XMLStreamWriter using XMLOutputFactory.

XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(outputStream);

Step 2: Write the header of the XML and proceed to write elements.


Step 3: After adding elements we can add attributes, character data, or CDATA.

xmlStreamWriter.writeAttribute("id", "10");
xmlStreamWriter.writeCharacters("hello world!");
xmlStreamWriter.writeCData("more text data");

Step 4: Closing opened elements


Step 5: Emptying elements or write comments, but do note it is an optional step

xmlStreamWriter.writeEmptyElement("used & new");
xmlStreamWriter.writeComment("Thank you!");

Step 6: Close and finish XML document.




// Java Program to Illustrate XMLStreamWriter in Java StAX
// Importing required classes
// Main class
public class StaxXMLStreamWriter {
    // Main driver method
    public static void main(String[] args)
        throws FileNotFoundException, XMLStreamException,
        // Try block to check for exceptions
        try {
            // File Path
            String filePath = "D:\\gfg_file.xml";
            // Creating FileWriter object
            Writer fileWriter = new FileWriter(filePath);
            // Getting the XMLOutputFactory instance
            XMLOutputFactory xmlOutputFactory
                = XMLOutputFactory.newInstance();
            // Creating XMLStreamWriter object from
            // xmlOutputFactory.
            XMLStreamWriter xmlStreamWriter
                = xmlOutputFactory.createXMLStreamWriter(
            // Addoing elements to xmlStreamWriter
            // Custom input element addition
            xmlStreamWriter.writeAttribute("id", "10");
            xmlStreamWriter.writeCharacters("hello world!");
            xmlStreamWriter.writeCData("more text data");
            xmlStreamWriter.writeEmptyElement("used & new");
            xmlStreamWriter.writeComment("Thank you!");
            // Writing the content on XML file and
            // close xmlStreamWriter using close() method
            // Display message for successful execution of
            // program
                "XML file created successfully.");
        // Catch block to handle exceptions
        catch (Exception e) {
            // Print the line number where exception occurs


<gfg id="10">hello world!
<![CDATA[more text data]]>
<used & new/>
<!--Thank you!-->


Streaming API for XML provides a very convenient, fast, and memory-efficient way to write XML documents without worrying about details and escaping special characters. It is a great alternative to DOM especially when you don’t need to keep and manage DOM tree in memory for any reason.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 16 Sep, 2021
Like Article
Save Article
Similar Reads
Complete Tutorials