How to write XML file in Java (DOM Parser)

Filed Under: Java

Earlier we learned how to read XML file and how to edit XML file in java using DOM Parser, today we will learn how to write an XML file in java using DOM Parser.

Here is the requirement for our XML file.

  1. The root element will be “Employees” with namespace “”. This root element will contain the list of Employees.
  2. The employee information will be written in “Employee” element. There will be two employees information in the XML file.
  3. Every employee has an attribute named “id”
  4. Employee element will have four elements – “name”, “age”, “role”, “gender”.

Here is the java program for above requirement.

package com.journaldev.xml;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class XMLWriterDOM {

    public static void main(String[] args) {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.newDocument();
            //add elements to Document
            Element rootElement =
                doc.createElementNS("", "Employees");
            //append root element to document

            //append first child element to root element
            rootElement.appendChild(getEmployee(doc, "1", "Pankaj", "29", "Java Developer", "Male"));

            //append second child
            rootElement.appendChild(getEmployee(doc, "2", "Lisa", "35", "Manager", "Female"));

            //for output to file, console
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            //for pretty print
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);

            //write to console or file
            StreamResult console = new StreamResult(System.out);
            StreamResult file = new StreamResult(new File("/Users/pankaj/emps.xml"));

            //write data
            transformer.transform(source, console);
            transformer.transform(source, file);

        } catch (Exception e) {

    private static Node getEmployee(Document doc, String id, String name, String age, String role,
            String gender) {
        Element employee = doc.createElement("Employee");

        //set id attribute
        employee.setAttribute("id", id);

        //create name element
        employee.appendChild(getEmployeeElements(doc, employee, "name", name));

        //create age element
        employee.appendChild(getEmployeeElements(doc, employee, "age", age));

        //create role element
        employee.appendChild(getEmployeeElements(doc, employee, "role", role));

        //create gender element
        employee.appendChild(getEmployeeElements(doc, employee, "gender", gender));

        return employee;

    //utility method to create text node
    private static Node getEmployeeElements(Document doc, Element element, String name, String value) {
        Element node = doc.createElement(name);
        return node;


Notice that I have created two StreamResult, one to print XML in console for debugging purpose and another to write it to file.

Here is the output XML from above program.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees xmlns="">
<Employee id="1">
<role>Java Developer</role>
<Employee id="2">

The XML is not formatted, if you want XML to be properly formatted, read format XML in java.


  1. MrBigglesworth says:

    LOL lots of lazy people want you to do their homework for them 馃槈

  2. Amit Jindal says:

    Hello Thanks for this code,

    Can you please provide a code for Reading data From Excel file from a path in system and convert it to XML document and save this to another location

  3. Vijay Kumar Kanta says:

    Great stuff. I was going through Google to find how to write XML (I already knew how to read), then I came across this and got super impressed with the clean demarcation of code and your lesson. Cheers!

  4. Priya says:

    Just awesome article. The code is very easy to understand. Thanks for sharing, Keep Blogging.

  5. Hary says:

    Hi Pankaj,

    thanks for your post. I have another problem regarding XML. Let say i have 2 xml files and i am comparing both. In case if a elemnt in file1 exists and is missing in file2, i want to delete that element from file1 and at the same time i want to copy that element in a newly created xml file. In orer to have a record what was missing in file2. My Problem is i can delete that particular element from file1 but can’t copy it to the new xml file.

  6. chandu gudipati says:

    0 down vote

    You can try this code., you will be getting the formatted output:

    transformer.setOutputProperty(OutputKeys.INDENT, “yes”);
    transformer.setOutputProperty(“{}indent-amount”, “10”);

  7. Praveen says:

    This is an excellent way of editing an XML. Although I need a solution were the XML format is retained, example editing a cache xml with below format should give me an output with the same format. Can you please suggest a way to do it ?

  8. Maxwell Queiroz says:


  9. najib says:

    Very very nice! It works like charm. Thank you so much!

  10. Bala says:

    Hi pankaj,

    Here i have a Question.. How to implement servlet in Struts Frame work.. Could explain clearly..

    1. geewhiz says:

      Would you like fries with that too?

      1. Farooque says:

        That was funny. Lol..hahahahaaaaaaa !!!!

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors