Java StAX XMLEventWriter

StAX XMLEventWriter:

StAX XMLEventReader class is used for writing the XML documents.

Methods of StAX XMLEventWriter:

1. add(Event event): It is used to add event containing elements to XML.

Example:

StaxTest.java

import java.io.FileWriter;
import java.io.Writer;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.events.XMLEvent;
 
/**
 * This class is used to create XML elements using Stax parser.
 * @author w3schools
 */
public class StaxTest {
	public static void main(String args[]){
	  try {
		//File Path
		String filePath = "D:\\classNew.xml";
 
		//Read XML file.
		Writer fileWriter = new FileWriter(filePath);
 
		//Get XMLOutputFactory instance.
		XMLOutputFactory xmlOutputFactory = 
                                        XMLOutputFactory.newInstance();
 
		//Create XMLEventWriter object.
		XMLEventWriter xmlEventWriter = 
                      xmlOutputFactory.createXMLEventWriter(fileWriter);
 
		//Get XMLEventFactory instance.
		XMLEventFactory  xmlEventFactory = 
                              XMLEventFactory.newInstance();
 
		//Create and add xmlEvents.
		XMLEvent xmlEvent=xmlEventFactory.createStartDocument();
		xmlEventWriter.add(xmlEvent);
 
		xmlEvent = xmlEventFactory.
                             createStartElement("class", "", "document");
		xmlEventWriter.add(xmlEvent);
 
		xmlEvent = xmlEventFactory.
                            createStartElement("student", "", "document");
		xmlEventWriter.add(xmlEvent);
 
		xmlEvent = xmlEventFactory.
                            createAttribute("name", "Prabhjot");
		xmlEventWriter.add(xmlEvent);
 
		xmlEvent = xmlEventFactory.
                            createEndElement("student", "", "document");
		xmlEventWriter.add(xmlEvent);
 
		xmlEvent = xmlEventFactory.
                            createEndElement("class", "", "document");
		xmlEventWriter.add(xmlEvent);
 
		//Write content on XML file and close xmlEventWriter.
		xmlEventWriter.flush();
		xmlEventWriter.close();
 
		System.out.println("XML file created successfully.");
	  } catch (Exception e) {
		e.printStackTrace();
	  }
	}
}

Output:

XML file created successfully.

classNew.xml

<?xml version="1.0"?>
<class:document>
<student:document name="Prabhjot"></student:document>
</class:document>

Download this example.
 
Next Topic: Java StAX XMLStreamReader example.
Previous Topic: Java StAX XMLEventReader example.