How to parse XML in Java

HOME

<?xml version = "1.0"?>
<department>
    <employee id = "10001">
        <firstname>Tom</firstname>
        <lastname>Mathew</lastname>
        <salary>25000</salary>
        <age>21</age>
    </employee>

    <employee id = "20001">
        <firstname>Katherine</firstname>
        <lastname>Jason</lastname>
        <salary>15000</salary>
        <age>20</age>
    </employee>

    <employee id = "30001">
        <firstname>David</firstname>
        <lastname>Mathew</lastname>
        <salary>35000</salary>
        <age>25</age>
    </employee>

    <employee id = "40001">
        <firstname>Berry</firstname>
        <lastname>Brian</lastname>
        <salary>50000</salary>
        <age>30</age>
    </employee>
</department>
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("employee");
System.out.println("Node Length :" + nodeList.getLength());
for (int temp = 0; temp < nodeList.getLength(); temp++) {

        Node node = nodeList.item(temp);
        System.out.println("\nCurrent Element :" + node.getNodeName());

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) node;

             //returns specific attribute
              System.out.println("Employee Id : " + eElement.getAttribute("id"));

            //returns a list of subelements of specified name
             System.out.println("First Name: " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
             System.out.println("Last Name: " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
             System.out.println("Salary: " + eElement.getElementsByTagName("salary").item(0).getTextContent());
             System.out.println("Age: " + eElement.getElementsByTagName("age").item(0).getTextContent());

    }

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;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

public class XMLParser {

    public static void main(String[] args) {

        try {

            //Create a DocumentBuilder
            File inputFile = new File("src/test/resources/testData/test.xml");
            System.out.println("Request :" + inputFile);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();

            //Extract the root element
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            NodeList nodeList = doc.getElementsByTagName("employee");
            System.out.println("Node Length :" + nodeList.getLength());

            for (int temp = 0; temp < nodeList.getLength(); temp++) {

                Node node = nodeList.item(temp);
                System.out.println("\nCurrent Element :" + node.getNodeName());

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) node;

                    //returns specific attribute
                    System.out.println("Employee Id : " + eElement.getAttribute("id"));

                    //returns a list of subelements of specified name
                    System.out.println("First Name: " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
                    System.out.println("Last Name: " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                    System.out.println("Salary: " + eElement.getElementsByTagName("salary").item(0).getTextContent());
                    System.out.println("Age: " + eElement.getElementsByTagName("age").item(0).getTextContent());

                }
            }

        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
    }

}

<?xml version = "1.0"?>
<cars>
    <sportscar company = "Porsce">
        <carname type = "formula one">Porsche 718 Boxster</carname>
        <carname type = "sports car">Porsche 718 Cayman</carname>
        <carname type = "sports car">2024 Porsche Panamera</carname>
    </sportscar>

    <supercars company = "Lamborgini">
        <carname>Lamborghini Aventador</carname>
        <carname>Lamborghini Reventon</carname>
        <carname>Lamborghini Gallardo</carname>
    </supercars>

    <supercars company = "Audi">
        <carname>Audi R8</carname>
        <carname>Audi Q8</carname>
        <carname>Audi Q6 e-tron</carname>
    </supercars>
</cars>

package com.example.XML;

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;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

public class ComplexXMLParser {

    public static void main(String[] args) {

        try {

            //Create a DocumentBuilder
            File inputFile = new File("src/test/resources/testData/test4.xml");
            System.out.println("Request :" + inputFile);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();

            //Extract the root element
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            NodeList sportscarNodeList = doc.getElementsByTagName("sportscar");
           // System.out.println("Node Length :" + nodeList.getLength());

            for (int temp = 0; temp < sportscarNodeList.getLength(); temp++) {

                Node node = sportscarNodeList.item(temp);
                System.out.println("\nCurrent Element :" + node.getNodeName());

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) node;

                    //returns specific attribute
                    System.out.println("sportscar : " + eElement.getAttribute("company"));

                    NodeList sportcarNameList = eElement.getElementsByTagName("carname");

                    for (int count = 0; count < sportcarNameList.getLength(); count++) {
                        Node node1 = sportcarNameList.item(count);

                        if (node1.getNodeType() == node1.ELEMENT_NODE) {
                            Element car = (Element) node1;

                            System.out.print("\ncar type : " + car.getAttribute("type"));
                            System.out.print("\ncar name : " + car.getTextContent());

                        }
                    }
                }

            }

            System.out.println("\n====================================================");
            NodeList supercarsNodeList = doc.getElementsByTagName("supercars");
            // System.out.println("Node Length :" + nodeList.getLength());

            for (int temp = 0; temp < supercarsNodeList.getLength(); temp++) {

                Node node1 = supercarsNodeList.item(temp);
                System.out.println("\nCurrent Element :" + node1.getNodeName());

                if (node1.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) node1;

                    //returns specific attribute
                    System.out.println("supercars : " + eElement.getAttribute("company"));

                    NodeList supercarsNameList = eElement.getElementsByTagName("carname");

                    for (int count = 0; count < supercarsNameList.getLength(); count++) {
                        Node node2 = supercarsNameList.item(count);

                        if (node1.getNodeType() == node2.ELEMENT_NODE) {
                            Element car = (Element) node2;

                            System.out.print("car name : " + car.getTextContent()+"\n");

                        }
                    }
                }

            }

        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
    }

}

Java Tutorials

Java is a general-purpose programming language that is a concurrent, class-based, and object-oriented language. Java follows the concept of “write once and run anywhere (WORA).” This means that compiled Java code can be run on all different platforms that support Java. There’s no need for recompilation.

Eclipse IDE

Chapter 1 How to Download and Install Eclipse IDE
Chapter 2 How to Clone a project from GitLab using Eclipse
Chapter 3 How to Export Eclipse projects to GitLab

IntelliJ IDE

Chapter 1 How to install IntelliJ on Windows
Chapter 2 How to create a Java project in IntelliJ
Chapter 3 How to Clone a project from GitLab using IntelliJ
Chapter 4 How to Export IntelliJ project to GitLab

Basics of Java

Chapter 1 How to Download & Install Java JDK 11 in Windows
Chapter 2 Data Types and Operators in Java
Chapter 3 Decision Making in Java – If, If Else, Switch, Break, Continue
Chapter 4 Loop Control Statements in Java – For, While, Do While, Enhanched For Loop
Chapter 5 String Manipulation
Chapter 6 Difference between == and equals() method in Java
Chapter 7 Arrays in Java
Chapter 8 Java Access Modifiers: Explained with Examples
Chapter 9 ArrayList in Java
Chapter 10 How to compare ArrayLists – contains?
Chapter 11 How to compare ArrayLists – containsAll method?
Chapter 12 Methods in Java
Chapter 13 Method Overloading in Java
Chapter 14 Constructors in Java   
Chapter 15 This Keyword in Java   
Chapter 16 Static Keyword – Static Variable and Static Method in Java
Chapter 17 Difference between Static Method and Non-Static Method
Chapter 18 How to use Java Lambda expression to create thread via Runnable function
Chapter 19 runAsync and supplyAsync in ComputableFuture in Java8
Chapter 20 HashMap in Java
Chapter 21 LinkedHashMap in Java
Chapter 22 Iterators in Java

OOPs Concepts

Chapter 1 Class and Object in Java
Chapter 2 Inheritance in Java
Chapter 3 Encapsulation in Java
Chapter 4 Polymorphism in Java
Chapter 5 Abstraction in Java
Chapter 6 Interface in Java
Chapter 7 Difference between Abstract Class and Interface

Exceptions in Java

Chapter 1 Exception Handling in Java
Chapter 2 Java Exceptions Tutorial: Built-in and User-defined Exceptions
Chapter 3 Flow control in try catch finally in Java
Chapter 4 Multiple Catch Exceptions
Chapter 5 Throw in Java
Chapter 6 Throws in Java

Data Handling (Excel Manipulation)

Chapter 1 How to download and install Apache POI
Chapter 2 Reading Excel Data with Apache POI in Java
Chapter 3 How to Write Data to Excel File in Java using Apache POI
Chapter 4 How to update existing excel in Java
Chapter 5 Java Excel Tutorial: Creating Excel with Formulas Using Apache POI
Chapter 6 Change Font Style in Excel with Apache POI – NEW

Multiple Choice Questions

Chapter 1 Multiple questions on Exception Handling in Java

Java Library

Chapter 1 AssertJ – Fluent Assertions in Java