Read XML File

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to read an XML file using Java. We will be using a sample XML file to demonstrate reading the file using Java code. XML is a markup language used to store and transport data.

Create a sample XML file

We will be using a sample XML file students.xml as an example. It contains some data about students and we will read that using Java code.

Create a new file named students.xml in the ~/project directory with the following content:

<students>
    <student id="101">
        <Name>John</Name>
        <id>11001</id>
        <location>India</location>
    </student>
    <student id="102">
        <Name>Alex</Name>
        <id>11002</id>
        <location>Russia</location>
    </student>
    <student id="103">
        <Name>Rohan</Name>
        <id>11003</id>
        <location>USA</location>
    </student>
</students>

Import the required libraries

We will be using the following libraries to read an XML file using Java code:

  • org.w3c.dom.*
  • javax.xml.parsers.*

Add the following statements at the beginning of the code file to import the required libraries:

import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import java.io.*;

Parse the XML file

Create a new Java class named Main in the ~/project directory with the following content:

public class Main {
    public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
        DocumentBuilderFactory dBfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = dBfactory.newDocumentBuilder();
        // Fetch XML File
        Document document = builder.parse(new File("students.xml"));
        document.getDocumentElement().normalize();
        //Get root node
        Element root = document.getDocumentElement();
        System.out.println(root.getNodeName());
        //Get all students
        NodeList nList = document.getElementsByTagName("student");
        System.out.println(".................................");
    }
}

We have created an instance of the builder and parsed the XML file using the parse method. After that, we get the root element of the document and normalise it and then print its name. After that, we get all the students using the getElementsByTagName method and print a separator.

Extract data from each element

To extract data from each element, we will iterate through each tag of the document using a loop. For each student, we will get their details such as ID, Name, Roll No, and Location.

Add the following code inside the loop:

Node node = nList.item(i);
System.out.println();    //Just a separator
if (node.getNodeType() == Node.ELEMENT_NODE) {
    //Print each student's detail
    Element element = (Element) node;
    System.out.println("Student id : " + element.getAttribute("id"));
    System.out.println("Name : " + element.getElementsByTagName("Name").item(0).getTextContent());
    System.out.println("Roll No : " + element.getElementsByTagName("id").item(0).getTextContent());
    System.out.println("Location : " + element.getElementsByTagName("location").item(0).getTextContent());
}

The above code will extract the data from each element of the XML file. Using the getAttribute method, the ID of each student is retrieved. Using the getElementsByTagName and getTextContent methods, the Name, Roll No, and Location of each student are retrieved.

Run the Java code

Compile and run the code in the terminal:

javac Main.java && java Main

You should see the following output:

students
.................................

Student id : 101
Name : John
Roll No : 11001
Location : India

Student id : 102
Name : Alex
Roll No : 11002
Location : Russia

Student id : 103
Name : Rohan
Roll No : 11003
Location : USA

Summary

In this lab, we have learned how to read an XML file using Java code. We have learned how to import required libraries, parse an XML file, iterate through each node of the root element, and extract data from each element. You can use this knowledge to read any XML file using Java and extract data from it.

Other Java Tutorials you may like