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

In this example, we show you how to use JDOM parser to create document, element and attribute in a XML file.

1. XML File

At the end of this example, following XML file will be created.

File : file.xml


<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff id="1">
    <firstname>yong</firstname>
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>199999</salary>
  </staff>
  <staff id="2">
    <firstname>low</firstname>
    <lastname>yin fong</lastname>
    <nickname>fong fong</nickname>
    <salary>188888</salary>
  </staff>
</company>

3. JDOM Example

JDOM example to create above XML file.


import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class WriteXMLFile {
	public static void main(String[] args) {

	  try {

		Element company = new Element("company");
		Document doc = new Document(company);
		doc.setRootElement(company);

		Element staff = new Element("staff");
		staff.setAttribute(new Attribute("id", "1"));
		staff.addContent(new Element("firstname").setText("yong"));
		staff.addContent(new Element("lastname").setText("mook kim"));
		staff.addContent(new Element("nickname").setText("mkyong"));
		staff.addContent(new Element("salary").setText("199999"));

		doc.getRootElement().addContent(staff);

		Element staff2 = new Element("staff");
		staff2.setAttribute(new Attribute("id", "2"));
		staff2.addContent(new Element("firstname").setText("low"));
		staff2.addContent(new Element("lastname").setText("yin fong"));
		staff2.addContent(new Element("nickname").setText("fong fong"));
		staff2.addContent(new Element("salary").setText("188888"));

		doc.getRootElement().addContent(staff2);

		// new XMLOutputter().output(doc, System.out);
		XMLOutputter xmlOutput = new XMLOutputter();

		// display nice nice
		xmlOutput.setFormat(Format.getPrettyFormat());
		xmlOutput.output(doc, new FileWriter("c:\\file.xml"));

		System.out.println("File Saved!");
	  } catch (IOException io) {
		System.out.println(io.getMessage());
	  }
	}
}

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
PranayAiran
Guest
PranayAiran

Hi Thanks for the tutorial, in the new version of jdom this line doc.setRootElement(company); is throwing error, you don’t need to set the root element again if you create a document object with the same element. so only Document doc = new Document(company); if sufficient

Thanks
Pranay

MaraOsegueda
Guest
MaraOsegueda

Muchas gracias! Estoy de acuerdo con PranayAiran… pero se arregla rapido y muy practica la herramienta jdom.

Gracias mkyong..!!!

Mickey
Guest
Mickey

Very Usefull, Thanks

Palak Mathur
Guest
Palak Mathur

Hi,

I think, the part of the code:

doc.setRootElement(company);

is not required as

 Document doc = new Document(company);

will create the document with rootElement as “Company”.

So the doc.setRootElement(company) should throw a runtime error.

Troy Johansson West
Guest
Troy Johansson West

I ran into the same issue, after a little Google searching I just worked around it by not setting the Root Element :-)

Manasi Soman
Guest
Manasi Soman

Thank you so so much!!

CHERRAD CHAREF EDDINE
Guest
CHERRAD CHAREF EDDINE

Hi . Please I need help ! i don’t find the XML file in the path

CHERRAD CHAREF EDDINE
Guest
CHERRAD CHAREF EDDINE

Hi !! how can I save this XML out I mean that i want it to be a physical out of my java code !! i don’t find it in this path c:\file.xml

Antonio Diéguez
Guest
Antonio Diéguez

not enough, XMLOutputter uses a default charset(UTF8 if you dont specify), but if you use FileWriter that will use the default (or setted) file encoding of the jvm in the platform (which may be very different). So you have to use FileOutputStream not FileWriter (or use FileWriter and change the default file encoding but its ugly)

hrushikesh
Guest
hrushikesh

Hi I need to split xml file into multiple xml files
is it possible???

Anthony
Guest
Anthony

Thanks man, amazing tutorial it helped me so much!
Keep it up!

sp
Guest
sp

Thank you very much for all ur posts, thay are so help full. I fallow many of them. Now have a question here..the same xml file how could we generate using sax? I am facing difficulty while setting attributes using SAX. like ..how do that in sax.

yong
mook kim
mkyong
199999

low
yin fong
fong fong
188888

sp
Guest
sp

Thank you very much for all ur posts, thay are so help full. I fallow many of them. Now have a question here..the same xml file how could we generate using sax? I am facing difficulty while setting attributes using SAX. like ..how do that in sax.

yong
mook kim
mkyong
199999

low
yin fong
fong fong
188888

Sachin More
Guest
Sachin More

I need to modify an XML and add custom tags in it, but are getting converted into > and < respectively. Can you please help me with this ?

Sachin More
Guest
Sachin More

Correction : I need to modify an XML and add custom tags in it, but less-than and greater-than brackets are getting converted into their unicodes (“<” and “>” respectively). Can you please help me with this ?

trackback
JDOM: Escribir o crear fichero XML desde Java | Apuntes de Programación

[…] Fuente: Mkyong […]

trackback
JDOM: | Apuntes de Programación

[…] Fuente: Mkyong […]

Fernando Soares
Guest
Fernando Soares

Thank you soooo much…
You helped me a lot..

an nguy?n
Guest
an nguy?n

It’s very good example about creating xml file. Thank u so much !!!!!!

Troy Johansson West
Guest
Troy Johansson West

Thank you for the JDOM2 examples for writing XML. I had dome a similar exercise using C#.NET and wanted to have a good XML write/reader for a Java Project I’m working on. The examples were very helpful. Following you on FB now.

Thanks again :-)

trackback
Java XML Tutorial

[…] Modify an existing XML file, by update the element and attribute, and also how to delete a element.Create a new XML file Create a XML file with new document, element and attribute.JAXB ExampleJAXB, using annotation to […]