Skip to content
Related Articles

Related Articles

Improve Article

XML EventWriter in Java StAX API

  • Last Updated : 27 Sep, 2021

Java StAX API was introduced in Java 6 and considered superior to DOM and SAX parsers. We can use Java StAX parser to read XML file and java Streaming API for XML (Java StAX) provides implementation for processing XML in java. The XMLEventWriter class in the Java StAX API allows you to write StAX XMLEvent’s either to a Writer, an OutputStream, or a Result (special JAXP object).

Methods provides by XMLEventWriter to write data into it:

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.

  • createStartDocument()
  • createStartElement()
  • createAttribute()
  • createNamespace()
  • createEndElement()

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

  1. XMLEventWriter 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.
  2. It is still possible to create not well-formed XML documents which for example contain more than one root element or miss namespace definition.

Procedure:



  • Creating an instance of XMLEventWriter
  • Writing the header of the XML
  • Create statements
  • Add elements so that we can addon attributes, namespaces.
  • Flush and close opened elements
  • Add try and catch block

They are as illustrated below as follows:

Step 1 : Create instance of XMLEventWriter using XMLOutputFactory.

XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEventWriter writer =factory.createXMLEventWriter(
new FileWriter("F:\\gfg-XmlFile.xml"));

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

XMLEvent event = eventFactory.createStartDocument();
event = eventFactory.createStartElement("GFG", "https://www.geeksforgeeks.org/", "document");

Step 3: After adding elements we can add attributes, namespace.

event = eventFactory.createNamespace("GeeksforGeeks-practice",
"https://practice.geeksforgeeks.org/");

writer.add(event);
event = eventFactory.createAttribute("attribute", "value");
writer.add(event);

Step 4: Flush and close opened elements.

writer.flush();
writer.close();

Step 5: Add try and catch block.

try 
    {
  ----------code------------
    } 
catch (XMLStreamException e) 
    {
     e.printStackTrace();
    } 
catch (IOException e) 
    {
    e.printStackTrace();
    }

Example

Java




// Java Program to Illustrate XML EventWriter in StAX API
 
// Importing required classes
import java.io.*;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Getting the XMLOutputFactory instance
        XMLOutputFactory factory
            = XMLOutputFactory.newInstance();
 
        // Getting the XMLEventFactory instance
        XMLEventFactory eventFactory
            = XMLEventFactory.newInstance();
 
        // Try block to check for exceptions
        try {
 
            // Creating EventWriter object
            XMLEventWriter writer
                = factory.createXMLEventWriter(
                    new FileWriter("F:\\gfg-XmlFile.xml"));
            XMLEvent event
                = eventFactory.createStartDocument();
            writer.add(event);
 
            // Creating a start element
            event = eventFactory.createStartElement(
                "GFG", "https://www.geeksforgeeks.org/",
                "document");
            writer.add(event);
 
            // Cteating namespace
            event = eventFactory.createNamespace(
                "GeeksforGeeks-practice",
                "https://practice.geeksforgeeks.org/");
            writer.add(event);
 
            // Setting attributes
            event = eventFactory.createAttribute(
                "attribute", "GFG");
            writer.add(event);
 
            // Lastly creating ana end element
            event = eventFactory.createEndElement(
                "GFG", "http://gfg.com", "document");
            writer.add(event);
 
            // Flush and close xmlEventWriter
            // using close() and flush() method
            // It is always a good practice
            writer.flush();
            writer.close();
        }
 
        // Catch block to handle exceptions
        catch (XMLStreamException e) {
 
            // Print line number where exception occurs
            // using printStacktrace() method
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

 

Output:

 

<?xml version='1.0' encoding='UTF-8'?>
<GFG:document xmlns:GeeksforGeeks-practice="https://practice.geeksforgeeks.org/" attribute="GFG>
</GFG:document>

Note: Streaming Event Writer 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 :