XML EventWriter in Java StAX
Last Updated :
25 Jul, 2022
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-based API (XMLEventWriter). For creating an XML structure, we specifically need to see a few important methods of XMLEventWriter. XMLEventWriter is the top level interface for writing XML documents.
Methods
| Description
|
---|
void add(XMLEvent event) | This will start adding an event to the output stream. Adding START_ELEMENT will help to open a new namespace scope. Finishing with END_ELEMENT the element is written and tags are closed. |
void add(XMLEventReader reader) | In case an entire stream to an output stream needs to be added, this is used. On an iteration basis, it will work on the inputStream by calling next() and it will be over until hasNext() returns false. This is the most efficient way to add as it iterates and loop over all the events and call add to each event. |
void close() | Finally, after constructing XML, this has to be called to free the resources that are associated. |
Example
Let us see a sample program on how to create an XML file named "geekauthordetails.xml" by using XMLEventWriter. In the whole set of programs, to bring a structured output,
- \n is used to make the data to be available on the new line
- \t is used to display the tabbed data contents.
If not required, we can remove them. Moreover, now the current program produces the output in the file named "geekauthordetails.xml". If we want to display the output in the console, we need to uncomment certain parts of the code.
try {
// This line creates the output in file. It has to be commented out
XMLEventWriter xmlEventWriter = xmlOutputFactory
.createXMLEventWriter(new FileOutputStream(geekAuthorFileName), "UTF-8");
// If we want to see the output directly in the console, instead of writing to the file, we can write to the console
// Just uncomment the below line and remove FileNotFoundException, we can achieve that
// XMLEventWriter xmlEventWriter = xmlOutputFactory.createXMLEventWriter(System.out);
}
GeekAuthorDetailsStaxXMLWriter.java
Java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
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.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
public class GeekAuthorDetailsStaxXMLWriter {
public static void main(String[] args) {
String geekAuthorFileName = "geekauthordetails.xml";
String rootElement = "GeekAuthors";
GeekAuthorDetailsStaxXMLWriter staxXMLWriter = new GeekAuthorDetailsStaxXMLWriter();
Map<String,String> geekAuthorDetailsElementsMap = new HashMap<String, String>();
// Information that needs to be available in xml.
// As a key value pair the details are given
geekAuthorDetailsElementsMap.put("authorName", "GeekA");
geekAuthorDetailsElementsMap.put("authorAge", "30");
geekAuthorDetailsElementsMap.put("articlesPublishedIn", "Java,Python,Database");
geekAuthorDetailsElementsMap.put("gender", "Female");
staxXMLWriter.writeXML(geekAuthorFileName, rootElement, geekAuthorDetailsElementsMap);
}
public void writeXML(String geekAuthorFileName, String rootElement, Map<String, String> geekAuthorDetailsElementsMap){
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
try {
XMLEventWriter xmlEventWriter = xmlOutputFactory
.createXMLEventWriter(new FileOutputStream(geekAuthorFileName), "UTF-8");
// If we want to see the output directly in the console, instead
// of writing to the file, we can write to the console
// Just uncomment the below line and remove FileNotFoundException,
// we can achieve that
// XMLEventWriter xmlEventWriter = xmlOutputFactory.createXMLEventWriter(System.out);
XMLEventFactory xmlEventFactory = XMLEventFactory.newInstance();
// To finish the ending, we need to end with \n, that is line feed
XMLEvent endIt = xmlEventFactory.createDTD("\n");
StartDocument startDocument = xmlEventFactory.createStartDocument();
xmlEventWriter.add(startDocument);
xmlEventWriter.add(endIt);
// Always rootElement will be the first
// tag for a structured XML document.
// Here it is GeekAuthors
StartElement configuredStartElement = xmlEventFactory.createStartElement("",
"", rootElement);
xmlEventWriter.add(configuredStartElement);
xmlEventWriter.add(endIt);
// Write the element nodes one by one
Set<String> elementNodes = geekAuthorDetailsElementsMap.keySet();
// All the elements are iterated using for loop and write perfectly
// with the createNode method
for(String key : elementNodes){
createNode(xmlEventWriter, key, geekAuthorDetailsElementsMap.get(key));
}
xmlEventWriter.add(xmlEventFactory.createEndElement("", "", rootElement));
xmlEventWriter.add(endIt);
xmlEventWriter.add(xmlEventFactory.createEndDocument());
xmlEventWriter.close();
// As we are writing to file, it is always good to
// handle exceptions related to file as well as XMLStreamException
} catch (FileNotFoundException | XMLStreamException e) {
e.printStackTrace();
}
}
private static void createNode(XMLEventWriter eventWriter, String keyElement,
String geekAuthorDetailsElementsMapValue) throws XMLStreamException {
XMLEventFactory xmlEventFactory = XMLEventFactory.newInstance();
XMLEvent endElement = xmlEventFactory.createDTD("\n");
XMLEvent tabElement = xmlEventFactory.createDTD("\t");
// Create Start node
StartElement startElement = xmlEventFactory.createStartElement("", "", keyElement);
// In order to beautify, a tab
// element is introduced
eventWriter.add(tabElement);
eventWriter.add(startElement);
// Create Content
Characters characters = xmlEventFactory.createCharacters(geekAuthorDetailsElementsMapValue);
eventWriter.add(characters);
// Create End node
EndElement endingElement = xmlEventFactory.createEndElement("", "", keyElement);
eventWriter.add(endingElement);
eventWriter.add(endElement);
}
}
Now, it has been set to write the output in the file itself. Hence we can able to get a file named "geekauthordetails.xml" mentioned in the location. Its contents are as follows. the image contains both styles if written to the console/if written to the file.
Output:
"geekauthordetails.xml" file contents as second image. First image represents console contentsConclusion
Though both SAX and StAX are stream-based or event-oriented XML parsers, SAX uses a "push" model, whereas StAX uses a "pull" model. via SAX, XML cannot be written and there is no support for it. But only in StAX, using XMLEventWriter, writing XML is possible and it is illustrated in the above example program.
Similar Reads
XML EventWriter in Java StAX API
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 XM
3 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
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
Character Stream Vs Byte Stream in Java
A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a method to sequentially access a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files. The java.io package provides classes that allow you to convert betwee
4 min read
javax.xml.crypto Package in Java
Common classes having the XML cryptography for the Package javax.xml.crypto. now this crypto package includes similar classes that are used to accessing XML cryptographic on its operations, such as creating an XML signature or encrypted XML data. There are two types of javax.xml.crypto classes in th
4 min read
Java.io.BufferedWriter class methods in Java
Bufferreader class writes text to character-output stream, buffering characters.Thus, providing efficient writing of single array, character and strings. A buffer size needs to be specified, if not it takes Default value. An output is immediately set to the underlying character or byte stream by the
5 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
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
CopyOnWriteArraySet in Java
In Java, the CopyOnWriteArraySet is the part of the java.util.concurrent package and is used to handle thread-safe operations in multi-threaded environments. It is ideal when the set is frequently read but infrequently modified. The set ensures safe access for multiple threads, as it creates a new c
6 min read