Dom parser to create xml file in java

Steps to create a new XML file:

1. Create a Document with DocumentBuilder class.
2. Define the XML data using Element class.
3. Write the whole data on a file using Transformer class.

Example:

DOMParserCreateTest.java

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
 
/**
 * This class is used to create XML document using DOM parser.
 * @author w3schools
 */
public class DOMParserCreateTest {
	public static void main(String args[]) {
		try {
		//File Path
		String filePath = "D:\\class.xml";
 
		//Create DocumentBuilderFactory object.
		DocumentBuilderFactory dbFactory = 
                             DocumentBuilderFactory.newInstance();
 
		//Get DocumentBuilder object.
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
 
		//Get Document object.
		Document document = dBuilder.newDocument();
 
		//Define root element.
		Element rootElement = document.createElement("class");
		document.appendChild(rootElement);
 
		//Define students element.
		Element students = document.createElement("students");
		rootElement.appendChild(students);
 
		//Set attribute to element.
		Attr attr = document.createAttribute("className");
		attr.setValue("MCA");
		students.setAttributeNode(attr);
 
		//Define StudentName elements.
		Element student1 = document.createElement("studentName");
		student1.appendChild(document.createTextNode("Prabhjot"));
		students.appendChild(student1);
 
		Element student2 = document.createElement("studentName");
		student2.appendChild(document.createTextNode("Nidhi Gupta"));
		students.appendChild(student2);
 
		//Write content into XML file.
		TransformerFactory transformerFactory = 
		                     TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(document);
		StreamResult result = new StreamResult(new File(filePath));
		transformer.transform(source, result);
 
		//For console Output.
		StreamResult consoleResult = new StreamResult(System.out);
		transformer.transform(source, consoleResult);			
	    } catch (Exception e) {
		e.printStackTrace();
	  }
       }
}

Output:

<?xml version="1.0" encoding="UTF-8"?>
<class>
<students className="MCA">
<studentName>Prabhjot</studentName>
<studentName>Nidhi Gupta</studentName>
</students>
</class>

Download this example.
 
Next Topic: DOM XML parser to modify xml file in java.
Previous Topic: DOM XML parser to parse XML file in java.