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.
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);






Thanks you so much. This code really helped me. I did run into an IO issue using the following code.
So I used this code from an earlier project I worked on which really worked for me!
Thank you again!
Best regards.
This encodes everything except quotes and apostrophes in the resulting XML. Any idea why?
Nice example though, thanks!
Inside an XML tag quotes and apostrophs are valid values. You can’t use them for element or attribute names and only need to take care inside attribute values.
Or did I not understand the question?
Nice article, clearly explained!
The problem with the DocumentBuilder is the memory requirement. So if you have very large XML to be written, you might run out of memory. In this case you can use SAX to write your XML. Opposite to common perception SAX not only can read, but also write an XML file. It automatically takes care of encoding etc. Sample code:
Original here: http://www.wissel.net/blog/d6plinks/SHWL-8B3G7U
The attributes of the elements are arranged in alphabetical order. Is there any way to arrange them in the order in which they are created?
The XML Specification clearly states that no application shall depend on the sequence of attributes of an XML element. If you do, you better get back to the drawing board.
hi can you please help me with your example. I am trying to write XML file, in a format listed below. It seem like I can not add second class element. Iam missing opening class element
?xml version=”1.0″ encoding=”UTF-8″ standalone=”no”?>abcddsdffggggggdsa
abcd
dsdff
gggg
ggdsa
sasas
ygfr
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
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.Document;
import org.w3c.dom.Element;
public class WriteXMLFile {
/**
* Creates a new instance of WriteXMLFile
*/
public WriteXMLFile() {
}
/**
* @param args the command line arguments
*/
public static void main(String argv[]) {
readFileAsString rfas = new readFileAsString();
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement(“School”);
doc.appendChild(rootElement);
// DataItem elements
Element staff = doc.createElement(“class”);
rootElement.appendChild(staff);
Element Name = doc.createElement(“name”);
Name.appendChild(doc.createTextNode(“abcd”));
staff.appendChild(Name);
Element LastName = doc.createElement(“lastname”);
LastName.appendChild(doc.createTextNode(“dsdff”));
staff.appendChild(LastName);
Element staff1 = doc.createElement(“class”);
rootElement.appendChild(staff1);
Element Name1 = doc.createElement(“name”);
Name1.appendChild(doc.createTextNode(“gggg”));
staff.appendChild(Name1);
Element LastName1 = doc.createElement(“lastname”);
LastName1.appendChild(doc.createTextNode(“ggdsa”));
staff.appendChild(LastName1);
//rootElement.appendChild(staff1);
// 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);
/*
* String resu = result.toString(); System.out.println(“TTTTTT
* “+resu.toString());
*/
transformer.transform(source, result);
transformer.toString();
//String xmlFile = “c:\\file.xml”;
try {
String kk = rfas.ReadFile(“c:\\file.xml”);
System.out.println(“TTTTTTTT” + kk);
} catch (IOException ex) {
Logger.getLogger(WriteXMLFile.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(“File saved!”);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
I have a string of xml which I would like to be the content of the xml file I am creating, is this posible?
thank you
i tried the method for my local C:\\file.xml.
But i want to create an xml in global server. Do you have any advice?
Just replace it with your network drive, and make sure your global server folder is writable.
hi how to convert an arrayList into xml file ? :)
May be just loop through the arrayList, and insert into XML file. What’s your stopper?
Hi,
have an issue, how to repeat those tags
like i want the output like this
yong
mook kim
mkyong
100000
yong
mook kim
mkyong
200000
yong
mook kim
mkyong
300000
The value of the salary is in a text file .
Please help
Hi, thanks for the nice code….
I have one issue with this….I created one .xml file using this code, but when I try to read this xml file from my other application….it says can not read because the file is being used by another process….could you please help me, if I need to close something somewhere at the end of the code.
Thanks & Regards
Hi,
Can anyone tell me, how to create standalone xml files using the same code???
i mean with attribute standalone =”yes”
Is there a way to write into the xml file but without erasing the previous existing code.
Because every time I run the already existing xml is erased??
Thanks
Great example yar.. Keep it up…
[...] Create XML file in Java using DOM library [...]
[...] Fuente | http://www.mkyong.com [...]
Can you help me?
I have a problem, this is
How to insert more new node and data of node inside xml file has existed?
Please help me
Thanks so much
Best Regards
Tony John
Hi man !
I need write more node to current XML , how i do it?
Thank you
Thanks for the tutorial
how can i give the file path in ubuntu linux to print the file in the Desktop??
Java.IO can get file path in both *nix and Win* easily, see this example, http://www.mkyong.com/java/how-to-construct-a-file-path-in-java/
But what you mean by “print the file in Desktop”?
i mean save the file in Desktop
the file path will be new File(“/home/prasath/Desktop/testing.xml”)
Thanks for the great writeup!!!
use java.IO , refer to this tutorial
http://www.mkyong.com/tutorials/java-io-tutorials/
Hi again,
As I checked to add atrribute you can write just:
staff.setAttribute(“id”, “1?); (without setAttributeNode method at all).
Currenctly I am trying to set bevahiour of empty elements. In default there are always serialized in short syntax e.g. , but sometimes there is needed to use full syntax .
Also there is another JDOM API (http://www.jdom.org/), but it is not included in JDK.
Really thanks and appreciated your sharing
Thanks a lot.
If you want to create XML without standalone attribute, there is easy way:
doc.setXmlStandalone(true);
Also you don’t have to create new reference for created atrribute :)
staff.setAttributeNode(doc.createAttribute(“id”));
staff.setAttribute(“id”, “1″);
Also that I checked output code is not indented (maybe you should correct this, because you provided XML with indentation above), but there is easy way to do that:
transformer.setOutputProperty(OutputKeys.INDENT, “yes”);
Best Regards
Nice, thanks for the tip about identation. But is there any way to get a better identation, I mean, like this:
blabla
qaz
because what I got after your tip was:
blabla
qaz
Upss, the xml code isn’t dispalyed! I didn’t knew. What I meant is the the all my xml code is aligned to the left. I was looking for some identation like the example showing on the top of the page. Thanks
[...] Create XML file Example to create a XML file with DOM class. [...]