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:
Conclusion
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.