CodesJava

Easy learning with example program codes

Java StAX XMLStreamWriter example


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 codesjava
 */
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.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.

 



Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki