How to update XML Documents Using Java DOM Parser

HOME

package XML.DOM;

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 javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;

public class DOM_ModifyXMLDemo {

    public static void main(String[] args) {

        try {

            //Create a DocumentBuilderFactory and DocumentBuilder
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Parse the XML file into a Document
            Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));

            // Normalize XML structure
            document.getDocumentElement().normalize();

            // Step 3: Update the XML content
            NodeList nodeList = document.getElementsByTagName("employee");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Element employee = (Element) nodeList.item(i);
                String id = employee.getAttribute("id");

                if ("1".equals(id)) {
                    Element position = (Element) employee.getElementsByTagName("position").item(0);
                    position.setTextContent("Consultant");
                }
            }

            //Traverse the nodes to normalize spaces in text nodes
            Node rootNode = document.getDocumentElement();
            normalizeSpace(rootNode);

            //Write changes back to the XML file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            //Writing updated content into the file
            DOMSource domSource = new DOMSource(document);

            StreamResult fileResult = new StreamResult(new File("src/test/resources/Payloads/UpdatedXML.xml"));
            transformer.transform(domSource, fileResult);

            // Print updated XML to console
            StreamResult consoleResult = new StreamResult(System.out);
            transformer.transform(domSource, consoleResult);

            System.out.println("\n XML file updated successfully!");

        } catch (ParserConfigurationException | TransformerException | IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }

    private static void normalizeSpace(Node node) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            String trimmedText = node.getTextContent().trim().replaceAll("\\s+", " ");
            node.setTextContent(trimmedText);
        }
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            normalizeSpace(children.item(i));
        }
    }
}

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));
 document.getDocumentElement().normalize();
  NodeList nodeList = document.getElementsByTagName("employee");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Element employee = (Element) nodeList.item(i);
                String id = employee.getAttribute("id");

                if ("1".equals(id)) {
                    Element position = (Element) employee.getElementsByTagName("position").item(0);
                    position.setTextContent("Consultant");
                }
            }
private static void normalizeSpace(Node node) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            String trimmedText = node.getTextContent().trim().replaceAll("\\s+", " ");
            node.setTextContent(trimmedText);
        }
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            normalizeSpace(children.item(i));
        }
    }

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();

transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Pretty print the XML
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

DOMSource domSource = new DOMSource(document);

 // Write XML to file
 StreamResult fileResult = new StreamResult(new File("src/test/resources/Payloads/UpdatedXML.xml"));
transformer.transform(domSource, fileResult);

StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(domSource, consoleResult);
try {
 } catch (ParserConfigurationException | TransformerException | IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }

package XML.DOM;

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 javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;

import static org.apache.commons.lang3.StringUtils.normalizeSpace;

public class DOM_ModifyXMLAddElementsDemo {

    public static void main(String[] args) {

        try {

            //Create a DocumentBuilderFactory and DocumentBuilder
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Parse the XML file into a Document
            Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));

            // Normalize XML structure
            document.getDocumentElement().normalize();

            //Locate the root element
            Element rootElement = document.getDocumentElement();

            // Create a new employee element
            Element employee = document.createElement("employee");
            employee.setAttribute("id", "4");

            // Create name element
            Element name = document.createElement("name");
            name.appendChild(document.createTextNode("Milly Mathew"));
            employee.appendChild(name);

            // Create position element
            Element position = document.createElement("position");
            position.appendChild(document.createTextNode("Architect"));
            employee.appendChild(position);

            //Append the new employee node to the root element
            rootElement.appendChild(employee);

            //Traverse the nodes to normalize spaces in text nodes
            Node rootNode = document.getDocumentElement();
            normalizeSpace(rootNode);

            //Write changes back to the XML file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            //Writing updated content into the file
            DOMSource domSource = new DOMSource(document);

            StreamResult fileResult = new StreamResult(new File("src/test/resources/Payloads/UpdatedXML1.xml"));
            transformer.transform(domSource, fileResult);

            // Print updated XML to console
            StreamResult consoleResult = new StreamResult(System.out);
            transformer.transform(domSource, consoleResult);

            System.out.println("\n XML file updated successfully!");

        } catch (ParserConfigurationException | TransformerException | IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }

    private static void normalizeSpace(Node node) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            String trimmedText = node.getTextContent().trim().replaceAll("\\s+", " ");
            node.setTextContent(trimmedText);
        }
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            normalizeSpace(children.item(i));
        }
    }

}

Element rootElement = document.getDocumentElement();
 // Create a new employee element
 Element employee = document.createElement("employee");
employee.setAttribute("id", "4");

// Create name element
Element name = document.createElement("name");
name.appendChild(document.createTextNode("Milly Mathew"));
employee.appendChild(name);

// Create position element
Element position = document.createElement("position");
position.appendChild(document.createTextNode("Architect"));
employee.appendChild(position);

//Append the new employee node to the root element
rootElement.appendChild(employee);

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to create XML Documents Using Java DOM Parser

HOME

An XML file contains data between the tags. This makes it complex to read compared to other file formats like docx and txt. There are two types of parsers which parse an XML file:

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import javax.xml.transform.OutputKeys;

public class CreateXMLDocument {

    public static void main(String[] args) {
        try {

            // Step 1: Create a DocumentBuilderFactory and DocumentBuilder
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Step 2: Create a new Document
            Document document = builder.newDocument();

            // Step 3: Create and append root element
            Element root = document.createElement("employees");
            document.appendChild(root);

            // Step 4: Create and append employee elements
            Element employee1 = document.createElement("employee");
            employee1.setAttribute("id", "1");
            Element name1 = document.createElement("Name");
            name1.appendChild(document.createTextNode("Jimmy Buffet"));
            Element id1 = document.createElement("Employee_Id");
            id1.appendChild(document.createTextNode(String.valueOf(10342256)));
            Element salary1 = document.createElement("Salary");
            salary1.appendChild(document.createTextNode(String.valueOf(5000.00)));
            employee1.appendChild(name1);
            employee1.appendChild(id1);
            employee1.appendChild(salary1);
            root.appendChild(employee1);

            Element employee2 = document.createElement("employee");
            employee2.setAttribute("id", "2");
            Element name2 = document.createElement("name");
            name2.appendChild(document.createTextNode("Jane Smith"));
            Element position2 = document.createElement("position");
            position2.appendChild(document.createTextNode("Project Manager"));
            employee2.appendChild(name2);
            employee2.appendChild(position2);
            root.appendChild(employee2);

            // Step 5: Write the content into an XML file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Pretty print the XML
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            DOMSource domSource = new DOMSource(document);

            // Write XML to file
            StreamResult fileResult = new StreamResult(new File("src/test/resources/Payloads/output.xml"));
            transformer.transform(domSource, fileResult);

           // Print XML to console
            StreamResult consoleResult = new StreamResult(System.out);
            transformer.transform(domSource, consoleResult);

            System.out.println("XML file created successfully!");

        } catch (ParserConfigurationException | TransformerException e) {
            e.printStackTrace();
        }
    }
}

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
 Document document = builder.newDocument();
Element root = document.createElement("employees");
document.appendChild(root);
Element employee1 = document.createElement("employee");
employee1.setAttribute("id", "1");
Element name1 = document.createElement("Name");
name1.appendChild(document.createTextNode("Jimmy Buffet"));
Element id1 = document.createElement("Employee_Id");
id1.appendChild(document.createTextNode(String.valueOf(10342256)));
Element salary1 = document.createElement("Salary");
salary1.appendChild(document.createTextNode(String.valueOf(5000.00)));
employee1.appendChild(name1);
employee1.appendChild(id1);
employee1.appendChild(salary1);
root.appendChild(employee1);

Element employee2 = document.createElement("employee");
employee2.setAttribute("id", "2");
Element name2 = document.createElement("name");
name2.appendChild(document.createTextNode("Jane Smith"));
Element position2 = document.createElement("position");
position2.appendChild(document.createTextNode("Project Manager"));
employee2.appendChild(name2);
employee2.appendChild(position2);
root.appendChild(employee2);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();

transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Pretty print the XML
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

DOMSource domSource = new DOMSource(document);

 // Write XML to file
 StreamResult fileResult = new StreamResult(new File("src/test/resources/Payloads/output.xml"));
transformer.transform(domSource, fileResult);

StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(domSource, consoleResult);

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to read XML using Java DOM Parser

HOME

An XML file contains data between the tags. This makes it complex to read compared to other file formats like docx and txt. There are two types of parsers which parse an XML file:

How to retrieve tag name from XML?

<?xml version="1.0"?>
<employees>
    <employee id="1">
        <name>John William</name>
        <position>Software Engineer</position>
    </employee>
    <employee id="2">
        <name>Jane Smith</name>
        <position>Project Manager</position>
    </employee>
    <employee id="3">
        <name>Lilly Smith</name>
        <position>Product Owner</position>
    </employee>
</employees>

package XML.DOM;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
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 XMLParserTagNameExample {

    public static void main(String[] args) {
        try {
            // Create a DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            // Obtain a DocumentBuilder from the factory
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Parse the XML file into a Document
            Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));

            // Normalize XML structure
            document.getDocumentElement().normalize();

            // Get the root element
            Element root = document.getDocumentElement();
            System.out.println("Root Element: " + root.getNodeName());
            System.out.println("-----------------------");

            // Retrieve the first employee element for extracting tag names
            NodeList nodeList = document.getElementsByTagName("employee");
            if (nodeList.getLength() > 0) {
                // If there is at least one employee, use it to print the element and attribute names
                Element employee = (Element) nodeList.item(0);

                    // Print the tag names
                    System.out.println("Employee ID Attribute Name: id");
                    System.out.println("Name Tag: " + employee.getElementsByTagName("name").item(0).getNodeName());
                    System.out.println("Position Tag: " + employee.getElementsByTagName("position").item(0).getNodeName());
                    System.out.println("-----------------------");
            }
        } catch (ParserConfigurationException e) {
            System.out.println("Parser configuration error occurred: " + e.getMessage());
        } catch (SAXException e) {
            System.out.println("SAX parsing error occurred: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO error when loading XML file: " + e.getMessage());
        } finally {
            System.out.println("XML parsing operation completed.");
        }
    }
}

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
 Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));
document.getDocumentElement().normalize();
Element root = document.getDocumentElement();
System.out.println("Root Element: " + root.getNodeName());
System.out.println("-----------------------");
NodeList nodeList = document.getElementsByTagName("employee");
            if (nodeList.getLength() > 0) {
                // If there is at least one employee, use it to print the element and attribute names
                Element employee = (Element) nodeList.item(0);

                    // Print the tag names
                    System.out.println("Employee ID Attribute Name: id");
                    System.out.println("Name Tag: " + employee.getElementsByTagName("name").item(0).getNodeName());
                    System.out.println("Position Tag: " + employee.getElementsByTagName("position").item(0).getNodeName());
                    System.out.println("-----------------------");
            }
        }

catch (ParserConfigurationException e) {
            System.out.println("Parser configuration error occurred: " + e.getMessage());
        } catch (SAXException e) {
            System.out.println("SAX parsing error occurred: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO error when loading XML file: " + e.getMessage());
        } finally {
            System.out.println("XML parsing operation completed.");
        }

package XML.DOM;

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;

import java.io.File;
import java.io.IOException;

public class SimpleXMLParserExample {

    public static void main(String[] args) {
        try {
            // Create a DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            // Obtain a DocumentBuilder from the factory
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Parse the XML file into a Document
            Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));

            // Normalize XML structure
            document.getDocumentElement().normalize();

            // Get the root element
            Element root = document.getDocumentElement();
            System.out.println("Root Element: " + root.getNodeName());
            System.out.println("-----------------------");

            // Retrieve all employee nodes
            NodeList nodeList = document.getElementsByTagName("employee");

            // Iterate over the employee nodes
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);

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

                    // Get the attribute and text content
                    String id = employee.getAttribute("id");
                    String name = employee.getElementsByTagName("name").item(0).getTextContent();
                    String position = employee.getElementsByTagName("position").item(0).getTextContent();

                    System.out.println("Employee ID: " + id);
                    System.out.println("Name: " + name);
                    System.out.println("Position: " + position);
                    System.out.println("-----------------------");
                }
            }
        } catch (ParserConfigurationException e) {
            System.out.println("Parser configuration error occurred: " + e.getMessage());
        } catch (SAXException e) {
            System.out.println("SAX parsing error occurred: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO error when loading XML file: " + e.getMessage());
        } finally {
            System.out.println("XML parsing operation completed.");
        }
    }
}
NodeList nodeList = document.getElementsByTagName("employee");
 for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);

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

                    // Get the attribute and text content
                    String id = employee.getAttribute("id");
                    String name = employee.getElementsByTagName("name").item(0).getTextContent();
                    String position = employee.getElementsByTagName("position").item(0).getTextContent();

                    System.out.println("Employee ID: " + id);
                    System.out.println("Name: " + name);
                    System.out.println("Position: " + position);
                    System.out.println("-----------------------");
                }
            }
        }

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

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();
        }
    }

}

How to retrieve XML Child Nodes in Java

HOME

<?xml version = "1.0"?>
<department>
    <employee>
        <firstname>Tom</firstname>
        <lastname>Mathew</lastname>
        <salary>25000</salary>
        <age>21</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());
  NodeList childNodes = node.getChildNodes();
                for (int i = 0; i < childNodes.getLength(); i++) {
                    Node childNode = childNodes.item(i);
                    if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                        System.out.println("Child node name " + i + ":" + childNode.getNodeName());
                        System.out.println("Child node value: " + i + ":" + childNode.getTextContent());

                    }
                }

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 ChildNodes {

    public static void main(String[] args) {

        try {
            //Create a DocumentBuilder
            File inputFile = new File("src/test/resources/testData/test1.xml");
            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());

                NodeList childNodes = node.getChildNodes();
                for (int i = 0; i < childNodes.getLength(); i++) {
                    Node childNode = childNodes.item(i);
                    if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                        System.out.println("Child node name " + i + ":" + childNode.getNodeName());
                        System.out.println("Child node value: " + i + ":" + childNode.getTextContent());

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

    }
}

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

    <employee id = "429">
        <firstname>Erika</firstname>
        <lastname>David</lastname>
        <salary>
                <fixed>
                    <fixed1>350000</fixed1>
                    <fixed2>200000</fixed2>
                </fixed>
                <bonus>5000</bonus>
        </salary>
        <age>29</age>
        <type>Permanent</type>
    </employee>
</department>

package com.example.XML;

import org.w3c.dom.Document;
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 ComplexChildNodes {

    public static void main(String[] args) {

        try {
            //Create a DocumentBuilder
            File inputFile = new File("src/test/resources/testData/test2.xml");
            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());

                NodeList childNodes = node.getChildNodes();
                for (int i = 0; i < childNodes.getLength(); i++) {
                    Node childNode = childNodes.item(i);

                    if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                        System.out.println("Child node name " + i + ":" + childNode.getNodeName());
                        System.out.println("Child node value: " + i + ":" + childNode.getTextContent());

                        for (int j = 0; j < childNode.getChildNodes().getLength(); j++) {
                            Node subChildNode = childNode.getChildNodes().item(j);
                            if (subChildNode.getNodeType() == Node.ELEMENT_NODE) {
                                {
                                    System.out.println("Sub Child node name " + j + ":" + subChildNode.getNodeName());
                                    System.out.println("Sub Child node value: " + j + ":" + subChildNode.getTextContent());
                                }
                            }
                        }
                    }

                }
            }

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

    }
}