StAX XMLStreamWriter class is used for writing the XML documents.
Methods of StAX XMLStreamWriter:
1. writeStartElement(String localName): It add start element of given name.
2. writeEndElement(String localName): It add end element of given name.
3. writeAttribute(String localName, String value): It write attribute to an element.
Example:
StaxTest.java
import java.io.FileWriter; import java.io.Writer; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; /** * This class is used to create XML elements using Stax parser. * @author w3spoint */ public class StaxTest { public static void main(String args[]){ try { //File Path String filePath = "D:\\classNew.xml"; //Create FileWriter object. Writer fileWriter = new FileWriter(filePath); //Get XMLOutputFactory instance. XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); //Create XMLStreamWriter object from xmlOutputFactory. XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(fileWriter); //Add elements to xmlStreamWriter. xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("class"); xmlStreamWriter.writeStartElement("student"); xmlStreamWriter.writeAttribute("name", "Rajesh Garg"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("student"); xmlStreamWriter.writeAttribute("name", "Harish Kansal"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); //Write content on XML file and close xmlStreamWriter. xmlStreamWriter.flush(); xmlStreamWriter.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> <student name="Rajesh Garg"></student> <student name="Harish Kansal"></student> </class> |
Download this example.
Previous Topic: Java StAX XMLStreamReader example.