How to create XML file in Java using DOM Parser?
Steps :
1) Create an instance of Document interface present in org.w3c.dom.* package.
For Creating an instance of Document interface we need to use DocumentBuilderFactory and DocumentBuilder classes present in javax.xml.parsers.* package.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
![]() |
Figure 1 |
Element root = document.createElement("Employees");
3) Make root as a child element of Document.
document.appendChild(root);
4) Now create child elements of root element Employees.
- Let say we want to store 4 Employees data in XML then one by one we have to create 4 elements as below. So child element is Employee.
- Each Employee should have some unique id that we can set as an attribute.
- Each Employee has some properties (name, age, gender etc). Values of these properties can be different for every Employee. So for each property we need to create element as below.
- We can set its value as below.
- One by one make these properties as a child element of Employee element as below.
- Finally make Employee element as a child element of Employees.
5) Create an instance of Transformer class present in javax.xml.transform.* package.
For creating an instance of Transformer class we need to use TransformerFactory class present in javax.xml.transform.* package.
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
6) Set xml file indentation (Optional)
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
7) Create an instance of DOMSource class present in javax.xml.transform.dom.* package and pass instance of Document interface created in step 1.
DOMSource source = new DOMSource(document);
8) Create an instance of StreamResult class present in javax.xml.transform.stream.* package.
For creating an instance of StreamResult class first we need to create an instance of File class present in java.io.* package.
File file = new File(location_of_xml_file);
StreamResult result = new StreamResult(file);
9) Transform XML Source to a Result.
transformer.transform(source, result);
8) Create an instance of StreamResult class present in javax.xml.transform.stream.* package.
For creating an instance of StreamResult class first we need to create an instance of File class present in java.io.* package.
File file = new File(location_of_xml_file);
StreamResult result = new StreamResult(file);
9) Transform XML Source to a Result.
transformer.transform(source, result);
Software Required:
- JDK
- Eclipse
- Maven
Note : I suggest to use latest version of all the software. If you need any help regarding these software installation please comment below I will help you.
Project Structure:
Java Code:
pom.xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | |
<modelVersion>4.0.0</modelVersion> | |
<groupId>com.javamultiplex</groupId> | |
<artifactId>DOM</artifactId> | |
<version>0.0.1-SNAPSHOT</version> | |
<build> | |
<pluginManagement> | |
<plugins> | |
<plugin> | |
<groupId>org.apache.maven.plugins</groupId> | |
<artifactId>maven-compiler-plugin</artifactId> | |
<version>3.6.1</version> | |
<configuration> | |
<source>1.8</source> | |
<target>1.8</target> | |
</configuration> | |
</plugin> | |
</plugins> | |
</pluginManagement> | |
</build> | |
</project> |
Employee.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex; | |
public class Employee { | |
private int id; | |
private String name; | |
private int age; | |
private String gender; | |
private String role; | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public int getAge() { | |
return age; | |
} | |
public void setAge(int age) { | |
this.age = age; | |
} | |
public String getGender() { | |
return gender; | |
} | |
public void setGender(String gender) { | |
this.gender = gender; | |
} | |
public String getRole() { | |
return role; | |
} | |
public void setRole(String role) { | |
this.role = role; | |
} | |
@Override | |
public String toString() { | |
return "Employee[id="+getId()+", name="+getName()+", gender="+getGender()+", age="+getAge()+", role="+getRole()+"]"; | |
} | |
public int getId() { | |
return id; | |
} | |
public void setId(int id) { | |
this.id = id; | |
} | |
} |
WriteXML.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
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 javax.xml.transform.stream.StreamResult; | |
import org.w3c.dom.Document; | |
import org.w3c.dom.Element; | |
public class WriteXML { | |
public static void main(String[] args) throws IOException { | |
BufferedReader input = null; | |
try { | |
input = new BufferedReader(new InputStreamReader(System.in)); | |
File file = new File("src/main/resources/employee.xml"); | |
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); | |
DocumentBuilder builder = factory.newDocumentBuilder(); | |
Document document = builder.newDocument(); | |
Element root = document.createElement("Employees"); | |
document.appendChild(root); | |
System.out.println("Enter how many employess data you want to add? : "); | |
int count = Integer.parseInt(input.readLine()); | |
String name = null, gender = null, role = null; | |
int age = 0; | |
Element element = null; | |
for (int i = 1; i <= count; i++) { | |
System.out.println("******* Employee : " + i + " ********"); | |
System.out.println("Enter name : "); | |
name = input.readLine(); | |
System.out.println("Enter gender : (male/female)"); | |
gender = input.readLine(); | |
System.out.println("Enter age : "); | |
age = Integer.parseInt(input.readLine()); | |
System.out.println("Enter role : "); | |
role = input.readLine(); | |
Employee employee = new Employee(); | |
employee.setName(name); | |
employee.setGender(gender); | |
employee.setAge(age); | |
employee.setRole(role); | |
element = getEmployeeNode(employee, i, document); | |
root.appendChild(element); | |
} | |
TransformerFactory tFactory = TransformerFactory.newInstance(); | |
Transformer transformer = tFactory.newTransformer(); | |
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); | |
DOMSource source = new DOMSource(document); | |
StreamResult result = new StreamResult(file); | |
transformer.transform(source, result); | |
System.out.println("Employee data has been added successfully."); | |
} catch (Exception exception) { | |
exception.printStackTrace(); | |
} finally { | |
if (input != null) { | |
input.close(); | |
} | |
} | |
} | |
private static Element getEmployeeNode(Employee employee, int id,Document document) { | |
Element element = document.createElement("Employee"); | |
element.setAttribute("id", String.valueOf(id)); | |
Element name = getPropertyNode("name", document, employee.getName()); | |
element.appendChild(name); | |
Element gender = getPropertyNode("gender", document,employee.getGender()); | |
element.appendChild(gender); | |
Element age = getPropertyNode("age", document,String.valueOf(employee.getAge())); | |
element.appendChild(age); | |
Element role = getPropertyNode("role", document, employee.getRole()); | |
element.appendChild(role); | |
return element; | |
} | |
private static Element getPropertyNode(String property, Document document,String value) { | |
Element element = document.createElement(property); | |
element.setTextContent(value); | |
return element; | |
} | |
} |
Output:
Figure 3 |
employee.xml
12345678910111213141516<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Employees>
<Employee id="1">
<name>Rohit</name>
<gender>male</gender>
<age>25</age>
<role>Programmer</role>
</Employee>
<Employee id="2">
<name>Bhavna</name>
<gender>female</gender>
<age>20</age>
<role>Student</role>
</Employee>
</Employees>
Download Project
References:
https://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/DocumentBuilder.html
Thank you friends, I hope you have clearly understood the solution of this problem. If you have any doubt, suggestion or query please feel free to comment below. You can also discuss this solution in our forum.
How to create XML file in Java using DOM Parser?
Reviewed by Rohit Agarwal
on
9/28/2017
Rating:

No comments:
Please provide your valuable comments. If you have any suggestion please share with me I will work on it and if you have any question or doubt please ask, don't hesitate. I am your friend, i will clarify all your doubts.