Skip to content
Related Articles

Related Articles

Improve Article

XMLStreamWriter in Java StAX

  • Last Updated : 16 Sep, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

  • 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.

Procedure:



  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.

xmlStreamWriter.writeStartElement("gfg");

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

xmlStreamWriter.writeEndElement();

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.

xmlStreamWriter.writeEndDocument();
xmlStreamWriter.close();

Example

Java




// Java Program to Illustrate XMLStreamWriter in Java StAX
  
// Importing required classes
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
  
// Main class
public class StaxXMLStreamWriter {
  
    // Main driver method
    public static void main(String[] args)
        throws FileNotFoundException, XMLStreamException,
               UnsupportedEncodingException
    {
  
        // 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(
                    fileWriter);
  
            // Addoing elements to xmlStreamWriter
            // Custom input element addition
            xmlStreamWriter.writeStartElement("gfg");
            xmlStreamWriter.writeAttribute("id", "10");
            xmlStreamWriter.writeCharacters("hello world!");
            xmlStreamWriter.writeCData("more text data");
            xmlStreamWriter.writeEndElement();
            xmlStreamWriter.writeEmptyElement("used & new");
            xmlStreamWriter.writeComment("Thank you!");
            xmlStreamWriter.writeEndDocument();
  
            // Writing the content on XML file and
            // close xmlStreamWriter using close() method
            xmlStreamWriter.flush();
            xmlStreamWriter.close();
  
            // Display message for successful execution of
            // program
            System.out.println(
                "XML file created successfully.");
        }
  
        // Catch block to handle exceptions
        catch (Exception e) {
  
            // Print the line number where exception occurs
            e.printStackTrace();
        }
    }
}

Output:

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

Conclusion: 

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :