How to read XML file in Java using DOM Parser?



  Steps:


1) Parse XML file or Create an instance of Document interface present in org.w3c.dom.* package.

For Creating an instance of Document interface we need to use DocumentBuilderFactory, DocumentBuilder classes present in javax.xml.parsers.* package and File class present in java.io.* package.

File file = new File(XML_file_location);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);

Read XML file Using DOM Parser
Figure 1

2) Get the root element of XML file. It returns Employees node.

String rootNode = document.getDocumentElement().getNodeName();

3) Get all the child nodes Employee of root node Employees. It returns the instance of NodeList interface present in org.w3c.dom.* package.

NodeList list = document.getElementsByTagName("Employee");

4) Now one by one examine each child node Employee and extract its data.

  • From all the child nodes that we got in Step 3 take one child node. It returns instance of Node interface present in org.w3c.dom.* package.
          Node node = list.item(i);
  • Check whether this node is Element node or not?
          if (node.getNodeType() == Node.ELEMENT_NODE) { }
  • If it is an Element node then typecast it and get its data (attributes and properties).
          Element element = (Element) node;
  • Get attribute value as below.
          String value=element.getAttribute(attribute_name);
  • Get property value as below.
           String value = element.getElementsByTagName(property_name).item(0).getTextContent();


Software Required:

  1. Java
  2. Eclipse
  3. 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 XML DOM Parser Project Structure Part2
Figure 2

Java Code:


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>


pom.xml

<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>
view raw pom.xml hosted with ❤ by GitHub

Employee.java

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;
}
}
view raw Employee.java hosted with ❤ by GitHub

ReadXML.java

package com.javamultiplex;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ReadXML {
public static void main(String[] args) {
File file = new File("src/main/resources/employee.xml");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
document.getDocumentElement().normalize();
String rootNode = document.getDocumentElement().getNodeName();
System.out.println("Root Element : " + rootNode);
List<Employee> employees = getEmployeesData(document);
for (Employee emp : employees) {
System.out.println(emp);
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
private static List<Employee> getEmployeesData(Document document) {
NodeList list = document.getElementsByTagName("Employee");
int length = list.getLength();
List<Employee> employees = new ArrayList<>();
for (int i = 0; i < length; i++) {
Node node = list.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
Employee emp = getEmployee(element);
employees.add(emp);
}
}
return employees;
}
private static Employee getEmployee(Element element) {
String id=element.getAttribute("id");
String name = getEmployeeDetails(element, "name");
String gender = getEmployeeDetails(element, "gender");
int age = Integer.parseInt(getEmployeeDetails(element, "age"));
String role = getEmployeeDetails(element, "role");
Employee emp = new Employee();
emp.setId(Integer.parseInt(id));
emp.setName(name);
emp.setAge(age);
emp.setGender(gender);
emp.setRole(role);
return emp;
}
private static String getEmployeeDetails(Element element, String property) {
String value = element.getElementsByTagName(property).item(0).getTextContent();
return value;
}
}
view raw ReadXML.java hosted with ❤ by GitHub

Output:


Java XML DOM Parser Output Part2
Figure 3

Download Project


Click here for more questions on DOM Parser.

References:


https://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/DocumentBuilderFactory.html
https://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/DocumentBuilder.html
https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Document.html
https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/NodeList.html
https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html
https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Element.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.

About Author:

I am simple guy with lot of ambitions. My main motive is to share whatever knowledge I have related to programming. With me you can easily learn how to solve any programming problem in Java.You can connect with me on social networking sites also.


Let's Get Connected: Linkedin | Facebook |

How to read XML file in Java using DOM Parser? How to read XML file in Java using DOM Parser? Reviewed by Rohit Agarwal on 9/29/2017 Rating: 5

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.

Powered by Blogger.