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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/SystemandDataProcessingGroup -.-> java/xml_dom4j("`XML/Dom4j`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/FileandIOManagementGroup -.-> java/files("`Files`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/if_else("`If...Else`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117444{{"`Read XML File`"}} java/xml_dom4j -.-> lab-117444{{"`Read XML File`"}} java/classes_objects -.-> lab-117444{{"`Read XML File`"}} java/modifiers -.-> lab-117444{{"`Read XML File`"}} java/oop -.-> lab-117444{{"`Read XML File`"}} java/packages_api -.-> lab-117444{{"`Read XML File`"}} java/files -.-> lab-117444{{"`Read XML File`"}} java/identifier -.-> lab-117444{{"`Read XML File`"}} java/arrays -.-> lab-117444{{"`Read XML File`"}} java/comments -.-> lab-117444{{"`Read XML File`"}} java/data_types -.-> lab-117444{{"`Read XML File`"}} java/if_else -.-> lab-117444{{"`Read XML File`"}} java/operators -.-> lab-117444{{"`Read XML File`"}} java/output -.-> lab-117444{{"`Read XML File`"}} java/strings -.-> lab-117444{{"`Read XML File`"}} java/system_methods -.-> lab-117444{{"`Read XML File`"}} end

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