How to create XML file in Java – (DOM Parser)

DOM provides many handy classes to create XML file easily. Firstly, you have to create a Document with DocumentBuilder class, define all the XML content – node, attribute with Element class. In last, use Transformer class to output the entire XML content to stream output, typically a File.

In this tutorial, we show you how to use DOM XML parser to create a XML file.

DOM Parser Example

At the end of the example, following XML file named “file.xml” will be created.


<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<company>
	<staff id="1">
		<firstname>yong</firstname>
		<lastname>mook kim</lastname>
		<nickname>mkyong</nickname>
		<salary>100000</salary>
	</staff>
</company>

File : WriteXMLFile.java – Java class to create a XML file.


package com.mkyong.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 WriteXMLFile {

	public static void main(String argv[]) {

	  try {

		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

		// root elements
		Document doc = docBuilder.newDocument();
		Element rootElement = doc.createElement("company");
		doc.appendChild(rootElement);

		// staff elements
		Element staff = doc.createElement("Staff");
		rootElement.appendChild(staff);

		// set attribute to staff element
		Attr attr = doc.createAttribute("id");
		attr.setValue("1");
		staff.setAttributeNode(attr);

		// shorten way
		// staff.setAttribute("id", "1");

		// firstname elements
		Element firstname = doc.createElement("firstname");
		firstname.appendChild(doc.createTextNode("yong"));
		staff.appendChild(firstname);

		// lastname elements
		Element lastname = doc.createElement("lastname");
		lastname.appendChild(doc.createTextNode("mook kim"));
		staff.appendChild(lastname);

		// nickname elements
		Element nickname = doc.createElement("nickname");
		nickname.appendChild(doc.createTextNode("mkyong"));
		staff.appendChild(nickname);

		// salary elements
		Element salary = doc.createElement("salary");
		salary.appendChild(doc.createTextNode("100000"));
		staff.appendChild(salary);

		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File("C:\\file.xml"));

		// Output to console for testing
		// StreamResult result = new StreamResult(System.out);

		transformer.transform(source, result);

		System.out.println("File saved!");

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

A new XML file is created in “C:\\file.xml“, with default UTF-8 encoded.

Note
For debugging, you can change the StreamResult to output the XML content to your console.


StreamResult result =  new StreamResult(System.out);
transformer.transform(source, result);

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Tim
Guest
Tim

You have a typo in the main class constructor, “argv” instead of “args” although it does not effect the code output.

Also can I suggest you add the line:

transformer.setOutputProperty(OutputKeys.INDENT, “yes”);

As this will give the output formatted with linebreaks and therefore much easier to read.

Nilesh Thakkar
Guest
Nilesh Thakkar

I am getting error as below:

Exception in thread “main” java.lang.AbstractMethodError: org.apache.xerces.dom.DocumentImpl.getXmlStandalone()Z

at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.setDocumentInfo(Unknown Source)

at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)

at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)

at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transformIdentity(Unknown Source)

at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source)

at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source)

at com.poster.scheduler.WriteXMLFile.main(WriteXMLFile.java:72)

Please suggest.

Sandeep Chavarkar
Guest
Sandeep Chavarkar

remove any reference to xerces.jar from your classpath

Anupam Mukherjee
Guest
Anupam Mukherjee

Thanks,can u tell me whether this is possible using arraylist,means I would like to take the input using hashmap and arraylist??

Sandeep
Guest
Sandeep

java.lang.AbstractMethodError: org.apache.crimson.tree.XmlDocument.getXmlStandalone()Z

Getting this exception

Sandeep Chavarkar
Guest
Sandeep Chavarkar

remove any reference to xerces.jar from your classpath.

Anurag
Guest
Anurag

Thank you!!! MK Yong

Arun Raj
Guest
Arun Raj

thanks it helped me.

Wesley K
Guest
Wesley K

Thank you so much! I really appreciate you posting this online. It really helped me out.

Vinoth vino
Guest
Vinoth vino

Good post. Very useful

dessie asrie
Guest
dessie asrie

how to create xml file document in java

Biplav
Guest
Biplav

How will it know it has to convert the file into xml??

Zubair
Guest
Zubair

Thanks, but we need example where we can read pre-existed xml file from url or so. and get content out of it and then write it to xml.

Guest
Guest
Guest

Hi, I am getting following error

CreateProcess() failed with error code 2:
The system cannot find the file specified.

Angel Eduardo Valecillos
Guest
Angel Eduardo Valecillos

can i use (Element[] data) to make an array of values and be able to make a clase for all my xml needs

Venkatesh Manohar
Guest
Venkatesh Manohar

Thanks a lot… I just refered your code example and was able to generate the xml as needed. Good going. Please keep posting code examples…

Sooks
Guest
Sooks

Thank you so much! That was incredibly helpful.

Abhishek
Guest
Abhishek

Thanks a lot. I had to do an assignment in Java for School and this and some other articles on the Website Helped so much. Thanks a lot

Lack of Understanding
Guest
Lack of Understanding

I like your tutorial but, most of your tutorials are lack of description. You did not give any description about the purpose of

TransformerFactory, Transformer, DOMSource class and so on.

Sanjiv Singh
Guest
Sanjiv Singh

I am using dom pasrer to create xml document where tag name start with digit. and it is giving exception. seems with java DOM parser , it is not allowed to have tagname starting with digit.

Same thing ,It is achievable in C#(dot-net) using System.Xml;

is there any way, i can achieve the same.

Program :
############
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement(“company”);
doc.appendChild(rootElement);
Element firstname = doc.createElement(“5firstname”);
firstname.appendChild(doc.createTextNode(“yong”));

rootElement.appendChild(firstname);

Exception :
###########
Exception in thread “main” org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.
at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.createElement(CoreDocumentImpl.java:618)
at com.impetus.avatar.WriteXMLFile.main(WriteXMLFile.java:25)

noobdeveloper
Guest
noobdeveloper

Hi can anyone help me. Im trying to create and xml with is filename as chinese characters. but when im using the code. its giving me %E5%A4.xml as filename. Hope you guys can help me. Here is my code

My file name supossed to be ??

documentBuilder = documentBuilderFactory.newDocumentBuilder();

document = (Document) documentBuilder.newDocument();

rootElement = (Element) document.createElement(“Settings”);

document.appendChild(rootElement);

transformerFactory = TransformerFactory.newInstance();

transformer = transformerFactory.newTransformer();

domSource = new DOMSource(document);

streamResult = new StreamResult(new File(path));

transformer.transform(domSource, streamResult);

Thanks

Hihere
Guest
Hihere

Hi..this really cool. Helped me.

Vinoth S
Guest
Vinoth S

Hi, In my case, i need to write severak xml content within a bigger xml file. Hence, i run a loop over the xml writer steps, i.e. add element, attribute, append child etc. But, can you tell me as to how to append the file everytime?

Pooja
Guest
Pooja

Hi,
This example is very helpful for me. But I want to set encoding value for generated XML file,as it is giving UTF-8 by default. I searched for any setXMLencoding() function but its not available.
Any help would be appreciated.
Thanks in advance.

Pooja
Guest
Pooja

I got solution.

transformer.setOutputProperty(OutputKeys.ENCODING, “Windows-1252”);

simon d
Guest
simon d

Helped a lot.
Thanks for the Tut but don’t you wanna add these two lines for autoindent?

transformer.setOutputProperty(OutputKeys.INDENT, “yes”);
transformer.setOutputProperty(“{http://xml.apache.org/xslt}indent-amount”, “2”);

Sam
Guest
Sam

thanks

Phil
Guest
Phil

Yes these lines made the resulting file look neat as opposed to all the xml tags on a single line as the example does

Yu (Danny) Sun
Guest
Yu (Danny) Sun

Thanks Simon,
These two lines are exactly what I want. Thank you very much! Bless.

Felipe
Guest
Felipe

Hi,
I don’t want to appear in the document “encoding = UTF-8”. Is there any way to do this?

Abhinav
Guest
Abhinav

Hi ..I too do not want the document to contain “encoding”, version. PLease help me out…

Nit
Guest
Nit

Hi,

I don’t want standalone=”no” in
Can you Please help?

Baris
Guest
Baris

If you want to disable “standalone”, just use the following code snippet:
doc.setXmlStandalone(true);

jenyk mondol
Guest
jenyk mondol

Hi..

Isnt there no way of creating xml with sax ? I am using ur method but my need is :
I have an xml file structure-

I need to make another xml out of it taking just “b” node to get structure

Right now I am using sax parser and storing xml as pojo. then using document builder to change pojo to xml. please suggest if there is better way to create xml out of xml as dom has memory issues I read.

jenyk mondol
Guest
jenyk mondol

Hi..

Isnt there no way of creating xml with sax ? I am using ur method but my need is :
I have an xml file structure-

I need to make another xml out of it taking just “b” node to get structure

Right now I am using sax parser and storing xml as pojo. then using document builder to change pojo to xml. please suggest if there is better way to create xml out of xml as dom has memory issues I read.

Prasanth
Guest
Prasanth

Very usefull… thanks..

Mario Silvano
Guest
Mario Silvano

Thanks man!, you did a great job!

Devraj
Guest
Devraj

Hi

How can we specify the order of the Elements?

Thanks
Devraj