Create XML File using DOM Parser of JAXP and Transformation APIs

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags , , , with 3 Comments on Create XML File using DOM Parser of JAXP and Transformation APIs

Example of Creating XML File using JAXP and Transformation APIs

We have already studied about :

  1. What is DOM and its structure
  2. JAXP for DOM Parsers

We will create a XML file using DOM parser and Transformation APIs in this article.

package com.G2.DOM;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CreateXMLFile {

	public static void main(String[] args)  {

		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.newDocument();

			Element ele = doc.createElement("Movies");

			Element childElement = doc.createElement("Movie");

			childElement.setAttribute("Type", "BollyWood");
			childElement.setAttribute("Name", "Lagaan");
			childElement.setAttribute("Actor", "Aamir Khan");

			//You can also use setTextContent() method to write between nodes



			//Save the Created XML on Local Disc using Transformation APIs as Discussed
			TransformerFactory tFactory = TransformerFactory.newInstance();
			Transformer transformer = tFactory.newTransformer();

                        //below 2 line are only for pretty look rendering of XML
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty("{}indent-amount", "4");

			Source s = new DOMSource(doc);
			Result res = new StreamResult( new FileOutputStream("ShivaSoft.xml"));
			transformer.transform(s, res);
			System.out.println("XML File Created Succesfully");

		} catch (ParserConfigurationException e) {
		catch(TransformerConfigurationException e)
		} catch (FileNotFoundException e) {
		} catch (TransformerException e) {


Note : The XML document can also be saved on local disc by serializing xml document first and then saving. But the serialization implementation differs for different APIS. So the best practice is using implementation independent method of saving xml document. To read more refer this URL:

Related posts

3 thoughts on “Create XML File using DOM Parser of JAXP and Transformation APIs”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.