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

could you please tell me, if i wanted to add any line at the top of the xml file, how can i add that?
or if i wanted to reference my xml to any DTD, how do i do that?
Hi,
Nice tutorial, but when i am running your example, it is creating file and adding records but they are not properly formatted, i mean the all are coming into a single line.
could you tell me how can i format this?
Thanks,
Punit
okay, this worked for me:
transformer.setOutputProperty(“{http://xml.apache.org/xslt}indent-amount”, “2″);
transformer.setOutputProperty(OutputKeys.INDENT, “yes”);
hi sir this tutorial is excellent
This helped, thank you.
How can i return the Document doc to the Method?
Thanks a lot ! All your examples are great and easy to understand.
thanks for posting this code :)
can you pls post link/code to impose indentation on the output xml file, currently it is coming in a single line..
How to append data to existing xml file in same java file and how to retrieve that data by writing code in same file
Hi , using your code I get an error on java xml tranform , it says that file is read only file system , please help me .
Wish you the best
Hey I followed your code I just need to know how do you append new data to the existing xml file…each time I add new date it is being overwritten…I learned that it can be done by reading the existing xml file and parsing but I am not sure how to do it….
Here is the code:
import java.io.*;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Log_XML {
/**
* @param args
*/
static String transaction_type,shop_no,terminal_no;
static int id=0;
public static void main(String[] args) throws IOException,DOMException
{
System.out.println(“Enter Id : “);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
id =Integer.parseInt(br.readLine());
System.out.println(“Enter Transaction type : “);
transaction_type = br.readLine();
System.out.println(“Shop no : “);
shop_no = br.readLine();
System.out.println(“Terminal no : “);
terminal_no = br.readLine();
write_XML_File(id);
}
public static void write_XML_File(int id)
{
String id_val=Integer.toString(id);
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// root log elements
Element log1 = doc.createElement(“log”);
doc.appendChild(log1);
// set attribute to log element
Attr attr = doc.createAttribute(“id”);
attr.setValue(id_val);
log1.setAttributeNode(attr);
// transaction type elements
Element transaction_type1 = doc.createElement(“transaction_type”);
transaction_type1.appendChild(doc.createTextNode(transaction_type));
log1.appendChild(transaction_type1);
// Shop no. elements
Element shop_no1 = doc.createElement(“shop_no”);
shop_no1.appendChild(doc.createTextNode(shop_no));
log1.appendChild(shop_no1);
// Terminal no. elements
Element terminal_no1 = doc.createElement(“terminal_no”);
terminal_no1.appendChild(doc.createTextNode(terminal_no));
log1.appendChild(terminal_no1);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, “yes”);
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(“D:\\log_file.xml”));
transformer.transform(source, result);
System.out.println(“File saved!”);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanx in advance your tutorials are very good !!!
Hi
I tried your code and it still overwrites. What am I missing?
hi
thanks a lot
this comment is very suitable for me
hii I want to design xml file for the values like in fusion charts X-axis and Y-axis..
can u give that source code pls…
Thanks in advance
we have in our xml content and this is getting converted to <p> while printing on the browser, because of this the text which is supposed to come in a para is not displayed as para. Could you please suggest on this. Thanks in advance
we have in our xml content and this is getting converted to <p> while printing on the browser, because of this the text which is supposed to come in a para is not coming as expected. Could you please suggest on this.
Thanks for your document. I try to set elements with database fields and I want to create sub child in child root. How can I do ? Thank you.
Am also looking for the same solution
Have built all the POJO classes as required having all the get/set for all the elements in XML document on which values need to be set.
Can you please let me know, if you have a solution now.. TIA
Thanks a lot for the code… Using this code I was able to create the file and save it in local system, but as per my requirement i need to create a file and place it in an other server, can you please advise on how this xml can be sent to other server. Thanks in advance.
The XML is posted to an OutputStream. You need to point it to the remote location. Nothing XML specific here. So it is beyond this tutorial. There is http cifs ftp just to name a few remote protocols.
thanks a lot….
Hello, thank you very much for your article. It’s really helpful :)
I’m wondering if you can help with a question. How do you append some children with the same name to a parent? For example I want to create this hierarchy:
X
Y
…
where the number of the child depends on the length of an array.
Thank you
Whoops sorry. I mean,
Like Pedro already said, after adding “transformer.setOutputProperty(OutputKeys.INDENT, “yes”);” the whole xml code is just aligned left. But how to indent it like in the example above? I ve searched everywhere, and everywhere it is only said to use OutputKeys.INDENT, “yes”. Of course the browsers do indent it automatically even without OutputKeys.INDENT, “yes”, but e.g. notepadd++ doesn’t. I would be very thankful, if someone provided the code indenting xml correctly.
I have no data in certain tags but i want the both starting and ending tags. I have tried with space in the tag value but its not working. Please suggest
Thank you sir, its really helpfull..
:)
I have a multiple source object. But transformer.transform takes one source and one result object. Can anybody tell me how to use trasform object for multiple source scenario? or do you have any other approach for this?Please help me.
Thank u very much…..for ur assistance!
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.
Thanks, it was very helpfull
looks good to me
Men, that is what i needed. TYVM
Thanks a lot it’s exactly that i want to do but i have the error :
The method serialize(Document) is undefined for the type XMLSerializer
for the line
What have you import in your project ?
Thank you
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…
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