How to create an XML file in Java

In this tutorial, we are going to see how to create an XML file in Java using JDOM Parser.

How to create an XML file in Java

Here is the XML file that we will create using JDOM Parser:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

Emily 18
New York


Here is the Java code to create the above XML file programmatically.

import org.jdom2.*;
import org.jdom2.output.*;

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

	  try {
		    Element entreprise = new Element("entreprise");
		    Document doc = new Document(entreprise);

		    Element employee1 = new Element("employee");
		    employee1.setAttribute(new Attribute("id", "1"));
		    employee1.addContent(new Element("name").setText("Alex"));
		    employee1.addContent(new Element("age").setText("25"));
		    employee1.addContent(new Element("address").setText("California"));

		    Element employee2 = new Element("employee");
		    employee2.setAttribute(new Attribute("id", "2"));
		    employee2.addContent(new Element("name").setText("Emily"));
		    employee2.addContent(new Element("age").setText("18"));
		    employee2.addContent(new Element("address").setText("New York"));

		    XMLOutputter xml = new XMLOutputter();
		    xml.output(doc, new FileWriter("c:\\test.xml"));

		    System.out.println("File was saved!");
	  } catch (Exception e) {


File was saved!


If you are running java on the command line, download the jdom library, then put the jar file in your project directory, and run the program as follows.

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *