Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)

How to read and parse XML file in Java?

Last updated on Apr 29,2024 51.4K Views

26 / 29 Blog from Java Programs

XML, eXtensible Markup Language is a markup language that defines a set of rules for encoding documents in a format that is readable. XML Parsing refers to going through an XML document in order to access or modify data. An XML Parser provides the required functionality to access or modify data in an XML document. In this article, let’s explore Java XML Parser in detail.

What is XML Parser?

The XML parser is a software library or a package that provides an interface for client applications to work with XML documents. It checks for proper format of the XML document and also validates the XML documents. 

Following diagram shows how XML parser interacts with XML documents:

xml parser - EdurekaYou can think of validation as another stage beyond parsing. As the component parts of the program are identified when parsing, a validating parser can compare them with the pattern laid down by the DTD or Schema, to check that they conform. 


The fundamental component of XML development is XML parsing. XML parsing for Java is a standalone XML component that parses an XML document (and at times also a standalone DTD or XML Schema) so that user program can process it. The figure below shows an XML document as input to the XML Parser for Java.


xml parser - Java XML Parser - Edureka

  • An XML document is sent as input to the XML Parser for Java
  • The DOM or SAX parser interface parses the XML document
  • The parsed XML is then transferred to the application for further processing

The XML Parser for Java might also include an integrated XSL Transformation (XSLT) Processor for transforming XML data using XSL stylesheets. Using the XSLT Processor, you can easily transform XML documents from XML to XML, XML to HTML, or virtually to any other text-based format.

Java provides a lot of options to parse XML documents. Some of the commonly used java XML parsers are:

  1. DOM Parser
  2. SAX Parser
  3. StAX Parser
  4. JAXB

In this article, let’s check out how to parse an XML File using the DOM Parser.

Java XML Parser – DOM

DOM stands for Document Object Model. DOM Parser is the easiest java XML parser to implement and learn. It parses an entire XML document, loads it into memory and constructs a tree representation of the document. Let’s consider a simple example to understand the concept.

For demo purpose, we will be using a file named Employees.xml. In the file, each employee has a unique ID, first and last name, age, and salary and the employees are separated by their IDs.

<?xml version="1.0" encoding="UTF-8"?>
     <Employee ID="1">
          <Firstname>Dean</Firstname >
     <Employee ID="2">
     <Employee ID="3">
     <Employee ID="4">

Also, in order to capture the notion of an employee, we create its respective Java class, called as shown below:

package MyPackage;

public class Employee {

	private String ID;
    private String Firstname;
    private String Lastname;
    private int age;
    private double salary;

    public Employee(String ID, String Firstname, String Lastname, int age, double salary) {
         this.ID = ID;
         this.Firstname = Firstname;
         this.Lastname = Lastname;
         this.age = age;
         this.salary = salary;

    public String toString() {
         return "<" + ID + ", " + Firstname + ", " + Lastname + ", " + age + ", " + salary + ">";


Parse an XML File using the DOM Parser

The Document Object Model(DOM) provides APIs that let you create, modify, delete, and rearrange nodes as needed. The DOM parser parses the entire XML document and loads the XML content into a Tree structure. Using the Node and NodeList classes, we can retrieve and modify the contents of an XML file.

A sample example program in Java that loads the content of an XML file and prints its contents is shown below:

package MyPackage;

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;
public class DomParserExample {
     public static void main(String[] args) throws ParserConfigurationException,
          SAXException, IOException {
    	//Get Document Builder
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          DocumentBuilder builder = factory.newDocumentBuilder();
          // Load the input XML document, parse it and return an instance of the
          // Document class.
          Document document = builder.parse(new File("Employees.xml"));
          List<Employee> employees = new ArrayList<Employee>();
          NodeList nodeList = document.getDocumentElement().getChildNodes();
          for (int i = 0; i < nodeList.getLength(); i++) {
               Node node = nodeList.item(i);
               if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element elem = (Element) node;
                    // Get the value of the ID attribute.
                    String ID = node.getAttributes().getNamedItem("ID").getNodeValue();
                    // Get the value of all sub-elements.
                    String firstname = elem.getElementsByTagName("Firstname")
                    String lastname = elem.getElementsByTagName("Lastname").item(0)
                    Integer age = Integer.parseInt(elem.getElementsByTagName("Age")
                    Double salary = Double.parseDouble(elem.getElementsByTagName("Salary")
                    employees.add(new Employee(ID, firstname, lastname, age, salary));
          // Print all employees.
          for (Employee empl: employees)

The execution of code happens as follows:

  • First, you need to import dom parser packages in the application
  • Next step is to create the DocumentBuilder object
  • Read the XML file to the Document object.
  • Parse and store the XML file in an instance of the Document class
  • When you find a node of type Node.ELEMENT_NODE, retrieve all its information and store them in an instance of the Employee class
  • Finally, print the information of all stored employees


<1, Dean, Winchester, 30, 2500.0>
<2, Sam, Davis, 22, 1500.0>
<3, Jake, Peralta, 24, 2000.0>
<4, Amy, Griffin, 25, 2250.0>

That’s how you can parse an XML file using the DOM Parser. DOM parser has its advantages and disadvantages.

Advantage and Disadvantages of DOM Parser


  • API is very simple to use 
  • It supports both read and write operations 
  • Preferred when random access to widely separated parts of a document is required


  • It is memory inefficient. As the file size increases, its performance deteriorates and consumes more memory
  • Comparatively slower than other XML parsers available in Java

This brings us to the end of this ‘Java XML Parser’ article. 

Make sure you practice as much as possible and revert your experience.  

Check out the Java Course Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. 

Encountering ‘No test result files matching test-xml‘ error in Azure DevOps? Get solutions and insights from the Edureka Community. Dive into troubleshooting steps and best practices to resolve this issue and ensure smooth CI/CD pipelines.

Got a question for us? Please mention it in the comments section of this ‘Java XML Parser’ article and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 3rd August,2024

3rd August

SAT&SUN (Weekend Batch)
View Details
Java Course Online

Class Starts on 28th September,2024

28th September

SAT&SUN (Weekend Batch)
View Details

Join the discussion

Browse Categories

webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to read and parse XML file in Java?