π Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this article, we will learn how to read XML file in Java. We will also learn how to parse XML file to Java object using DOM XML Parser. DOM XML parser parses the entire XML document and loads it into memory; then models it in a “TREE” structure for easy traversal or manipulation.
In short, it turns an XML file into DOM or Tree structure, and we have to traverse a node by node to get what you want.
Warning: DOM Parser is slow and consumes a lot of memory when it loads an XML document which contains a lot of data. Please consider SAX parser as a solution for it, SAX is faster than DOM and use less memory.
Development Process Steps
- Input users.xml File(XML file we will read)
- Create User class (populate XML data into User object)
- Program to Read XML File in Java using Java DOM Parser
1. Input users.xml File(XML file we will read)
Here is the XML file that will be read in this program.
<?xml version="1.0" encoding="UTF-8"?>
<Users>
<User>
<id>1</id>
<firstName>Ramesh</firstName>
<lastName>Fadatare</lastName>
<age>28</age>
<gender>Male</gender>
</User>
<User>
<id>2</id>
<firstName>John</firstName>
<lastName>Cena</lastName>
<age>45</age>
<gender>Male</gender>
</User>
<User>
<id>3</id>
<firstName>Tom</firstName>
<lastName>Cruise</lastName>
<age>40</age>
<gender>Male</gender>
</User>
</Users>
2. Create User class (populate XML data into User object)
So this XML is the list of users, to read this XML file we will create a bean object User and then we will parse the XML to get the list of users.
Here is the User bean object.
package net.javaguides.javaxmlparser.dom;
public class User {
private int id;
private String firstName;
private String lastName;
private int age;
private String gender;
public int getId() {
return id;
}
public void setId(int i) {
this.id = i;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
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;
}
@Override
public String toString() {
return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", gender=" +
gender + "]";
}
}
3. Program to Read XML File in Java using Java DOM Parser
Here is the java program that uses DOM Parser to read and parse XML file to get the list of User object.
package net.javaguides.javaxmlparser.dom;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Java DOM Parser to Read XML File in Java
* @author Ramesh Fadatare
*
*/
public class ReadXMLFileInJava {
public static void main(String[] args) {
String filePath = "users.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nodeList = doc.getElementsByTagName("User");
// now XML is loaded as Document in memory, lets convert it to Object List
List < User > userList = new ArrayList < User > ();
for (int i = 0; i < nodeList.getLength(); i++) {
userList.add(getUser(nodeList.item(i)));
}
// lets print User list information
for (User emp: userList) {
System.out.println(emp.toString());
}
} catch (SAXException | ParserConfigurationException | IOException e1) {
e1.printStackTrace();
}
}
private static User getUser(Node node) {
// XMLReaderDOM domReader = new XMLReaderDOM();
User user = new User();
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
user.setId(Integer.parseInt(getTagValue("id", element)));
user.setFirstName(getTagValue("firstName", element));
user.setLastName(getTagValue("lastName", element));
user.setGender(getTagValue("gender", element));
user.setAge(Integer.parseInt(getTagValue("age", element)));
}
return user;
}
private static String getTagValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}
}
The output of the above program:
Root element :Users
User [id=1, firstName=Ramesh, lastName=Fadatare, age=28, gender=Male]
User [id=2, firstName=John, lastName=Cena, age=45, gender=Male]
User [id=3, firstName=Tom, lastName=Cruise, age=40, gender=Male]
That’s all about how to read XML file or parse XML file in java.
Reference
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
π High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
π High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
π Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
π₯ Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
π₯ Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
π Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
π₯ Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
π Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
π₯ Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
π₯ Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
π₯ Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
π Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business

Comments
Post a Comment
Leave Comment