Java read xml dom parser example

htt‮p‬s://www.theitroad.com

Here's an example of how to read an XML file using DOM parser in Java:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.File;

public class DomParserExample {

    public static void main(String[] args) {
        try {
            File inputFile = new File("input.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("employee");
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Element eElement = (Element) nList.item(temp);
                System.out.println("Employee id : " + eElement.getAttribute("id"));
                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("Email : " + eElement.getElementsByTagName("email").item(0).getTextContent());
                System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, we first create a File object for the XML file we want to read. We then create a DocumentBuilderFactory and use it to create a DocumentBuilder. The DocumentBuilder is used to parse the XML file and create a Document object representing the XML. We then normalize the document to remove any empty nodes and whitespace. We use the getElementsByTagName method to obtain a list of all the employee elements in the document. We iterate over the list and extract the data for each employee, outputting it to the console.

Note that this code may throw exceptions such as ParserConfigurationException, SAXException, and IOException, so you should be prepared to handle these exceptions in your code.