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);
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: over here()

  • Pingback: he has a good point()

  • Pingback: alkaline water()

  • Pingback: loan payment plan()

  • Pingback: alkaline water brands()

  • Pingback: water ionizer()

  • Pingback: HD Coloring Pages()

  • Pingback: house blue()

  • Pingback: find a plumber in my area()

  • Pingback: plumbing access panel ceiling()

  • Pingback: locksmith kit()

  • Pingback: locksmithing pick's disease()

  • Pingback: electrician bible 1.2.4.2.4 apk()

  • Pingback: going here()

  • Pingback: pay per day loans plan()

  • Pingback: water ionizer pay plan loans()

  • Pingback: pay per day loan plans()

  • Pingback: stop parking()

  • Pingback: laan penge billigt()

  • Pingback: mobile porn()

  • Pingback: laan penge online()

  • Pingback: lan penge her og nu()

  • Pingback: parking()

  • Pingback: check out DIRECTV channels()

  • Pingback: tv online, online tv()

  • Pingback: Blue Coaster33()

  • 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”);

  • Felipe

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

  • Nit

    Hi,

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

    • Baris

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

  • 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

    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

    Very usefull… thanks..

  • http://www.mariosoftsolutions.com Mario Silvano

    Thanks man!, you did a great job!

  • Devraj

    Hi

    How can we specify the order of the Elements?

    Thanks
    Devraj

  • http://na ben

    the regular question where is the jar file for this…

  • ashish

    Hi
    I’m a big fan of this website and owner who create all these examples for us. this website is such a great help for me.

    well i have one problem

    i’m new in java coding actually
    i run this example and its working file :-)
    but whenever i want to add one more stuff element in this xml file it will overwrite and does not append under previous tag.

    well i used such a code like

    File file = new File(“e:\\myfile.xml”);
    FileWriter fw = new FileWriter(file.getName(),true);

    but this will not help
    please provide me this information as well , otherwise the entire example will be useless

    and yes last but not a least
    Thanks a lot

    • Daniel Schnell

      ashish has a good question about inputing multiple elements. I am curious about that as well.

      I am as well curious about how to name the file dynamically by what the user is entering.

      For example:
      If the user was asked what he/she wants it to be named. How do you set the file to be named as that?

      I think in groovy, you can do it something like:
      def file = new File(“${usersInput}”)

      How can you do something like this in java?

  • Melvin

    Really helped thanks.