DocumentBuilderDocumentBuilderFactorytransformTransformerTransformerFactory

Create XML File in Java using DOM parser example

In this tutorial we are going to see how to create XML File in Java using DOM parser. The basic idea is very simple. You construct the DOM object with the tree structure you want in the memory, and then you use a Transformer and a StreamResult in order to write the DOM object to a stream, in our case a File.

In short the basic steps one has to take in order to create an XML File withe a DOM Parser are:

  • Create a DocumentBuilder instance.
  • Create a Document from the above DocumentBuilder.
  • Create the elements you want using the Element class and its appendChild method.
  • Create a new Transformer instance and a new DOMSource instance.
  • Create a new StreamResult to the output stream you want to use.
  • Use transform method to write the DOM object to the output stream you want.

Let’s take a closer look at the code snippet that follows:

package com.javacodegeeks.java.core;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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;

public class CreateXMLFileJava {

	public static final String xmlFilePath = "C:\\Users\\nikos7\\Desktop\\files\\xmlfile.xml";

	public static void main(String argv[]) {

		try {

			DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();

			DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();

			Document document = documentBuilder.newDocument();

			// root element
			Element root = document.createElement("company");
			document.appendChild(root);

			// employee element
			Element employee = document.createElement("employee");

			root.appendChild(employee);

			// set an attribute to staff element
			Attr attr = document.createAttribute("id");
			attr.setValue("10");
			employee.setAttributeNode(attr);

			//you can also use staff.setAttribute("id", "1") for this

			// firstname element
			Element firstName = document.createElement("firstname");
			firstName.appendChild(document.createTextNode("James"));
			employee.appendChild(firstName);

			// lastname element
			Element lastname = document.createElement("lastname");
			lastname.appendChild(document.createTextNode("Harley"));
			employee.appendChild(lastname);

			// email element
			Element email = document.createElement("email");
			email.appendChild(document.createTextNode("james@example.org"));
			employee.appendChild(email);

			// department elements
			Element department = document.createElement("department");
			department.appendChild(document.createTextNode("Human Resources"));
			employee.appendChild(department);

			// create the xml file
			//transform the DOM Object to an XML File
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource domSource = new DOMSource(document);
			StreamResult streamResult = new StreamResult(new File(xmlFilePath));

			// If you use
			// StreamResult result = new StreamResult(System.out);
			// the output will be pushed to the standard output ...
			// You can use that for debugging 

			transformer.transform(domSource, streamResult);

			System.out.println("Done creating XML File");

		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (TransformerException tfe) {
			tfe.printStackTrace();
		}
	}
}

xmlfile.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
	<employee id="10">
		<firstname>James</firstname>
		<lastname>Harley</lastname>
		<email>james@example.org</email>
		<department>Human Resources</department>
	</employee>
</company>

This was an example on how to create XML File in Java using DOM parser.

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

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

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
amit
amit
4 years ago

I want to change standalone to YES

How to do this???

Yasin zeighami
Yasin zeighami
3 years ago
Reply to  amit
TransformerFactory transformerFactory = TransformerFactory.newInstance();

Transformer transformer = transformerFactory.newTransformer();

transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
Last edited 3 years ago by Yasin zeighami
Jothilakshmi
Jothilakshmi
4 years ago

java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DocumentImpl cannot be cast to javax.swing.text.Document

Am getting the above exception while running the code

paul
paul
4 years ago

After the execution, XML attributes are jumbling order and not coming up in a sequence order.

Praveena
Praveena
4 years ago

Hi.. Thank you for the this. I am seeing all elements expanded when i open the xml document in browser. How can I have collapsed when i open xml document in browser?

Back to top button