XMLStreamWriter in Java StAX

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:
writeStartDocument()
writeStartElement()
writeCharacters()
writeEndElement()
writeEndDocument()
There are certain limitations been attached with  XMLStreamWriter in java StAX of which primarily are as follows:
It is still possible to create not well-formed XML documents which for example contain more than one root element or miss namespace definition.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.
It is still possible to create not well-formed XML documents which for example contain more than one root element or miss namespace definition.
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:
Create instance of XMLStreamWriter using XMLOutputFactoryWrite the header of the XML and proceed to write elements.After adding elements we can add attributes, character data, or CDATAClose opened elementsEmptying elements or write commentsClose and finish XML document
Create instance of XMLStreamWriter using XMLOutputFactory
Write the header of the XML and proceed to write elements.
After adding elements we can add attributes, character data, or CDATA
Close opened elements
Emptying elements or write comments
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 classesimport 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 classpublic 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.
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java