XML EventWriter in Java StAX API
Last Updated :
17 Jan, 2022
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:
- createStartDocument()
- createStartElement()
- createAttribute()
- createNamespace()
- createEndElement()
There are certain limitations been attached with  XMLEventWriter in java StAX of which primarily are as follows:
- 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.
- 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);
// Creating 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.
Â
Similar Reads
XML EventWriter in Java StAX
Java StAX API is also called Java Streaming API for XML and it was introduced in Java 6. This is the most wanted API while considering DOM and SAX parsers. Â StAX consists of cursor-based API and iterator-based API. In this article, let us see how to prepare an XML file in java using StAX Iterator-ba
5 min read
XML Output Factory in Java StAX
StAX provides various classes to create XML stream readers, writers, and events by using the XMLInputFactory, XMLOutputFactory, and XMLEventFactory classes. In this article we're going to study about XML Output Factory . The class javax.xml.stream.XMLOutputFactory is a root component of the Java StA
3 min read
StAX XML Parser in Java
This article focuses on how one can parse a XML file in Java.XML : XML stands for eXtensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable. Thatâs why, the design goals of XML emphasize simplicity, generality, and usability acros
6 min read
Java.io.FilterWriter class in Java
Abstract class for writing filtered character streams. The abstract class FilterWriter itself provides default methods that pass all requests to the contained stream. Subclasses of FilterWriter should override some of these methods and may also provide additional methods and fields. Constructor : pr
2 min read
Attributes in Servlets | Java
An attribute in servlet is an object that can be set, get or removed by the following aspects Request Scope Application Scope Session Scope To pass the value from servlet to html/jsp files, setAttribute() method is called by the request object. setAttribute() method takes an input as an object which
3 min read
What are XML Entities ?
XML is a way to organize information on the internet. It's like a recipe that tells computers how to understand and use the information. Entities in XML are like ingredients in a recipe. They help you define and reuse parts of your information, making it easier to manage and share. What is XML?XML s
8 min read
Different Ways to Copy Files in Java
There are mainly 3 ways to copy files using java language. They are as given below: Using File Stream (Naive method)Using FileChannel ClassUsing Files class. Note: There are many other methods like Apache Commons IO FileUtils but we are solely discussing copying files using java classes. Method 1: U
6 min read
Java Architecture for XML Binding ( JAXB ) | Set-1
Java Architecture for XML Binding (JAXB) defines an API for reading and writing Java objects to and from XML documents. JAXB gives Java developers an efficient and standard way of mapping between XML and Java code. JAXB makes it easier for developers to extend their applications with XML and Web Ser
4 min read
How to Create XML in JavaScript ?
In JavaScript, XML documents can be created using various approaches. You can define elements, attributes, and content to structure the XML data, and then serialize it into a string for use or storage. There are several approaches to creating XML in JavaScript which are as follows: Table of Content
2 min read
Create a Temporary File in Java
In Java, we can create a temporary file using an existing method known as File.createTempFile() method which creates a new empty file on the specified directory. The createTempFile() function creates a temporary file in a given directory (if the directory is not mentioned then a default directory is
4 min read