Today we will learn how to read the XML file in Java. We will also learn how to parse an XML file in java to object using DOM parser.
DOM XML Parser is easiest to understand. It loads the XML object into memory as Document, then you can easily traverse different elements and nodes in the object. The traversing of elements and nodes are not required to be in order.
How to read XML File in Java
DOM Parser are good for small XML documents but since it loads complete XML file into memory, it’s not good for large XML files. For large XML files, you should use SAX Parser.
In this tutorial, we will read the XML file and parse it to create an object from it.
Here is the XML file that will be read in this program.
employee.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0"?> <Employees> <Employee> <name>Pankaj</name> <age>29</age> <role>Java Developer</role> <gender>Male</gender> </Employee> <Employee> <name>Lisa</name> <age>35</age> <role>CSS Developer</role> <gender>Female</gender> </Employee> </Employees> |
So this XML is the list of employees, to read this XML file I will create a bean object Employee and then we will parse the XML to get the list of employees.
Here is the Employee bean object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.journaldev.xml; public class Employee { private String name; private String gender; private int age; private String role; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } @Override public String toString() { return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender + " Role=" + this.role; } } |
Notice that I have overridden toString() method to print useful information about the employee.
Read this post to know you should always use @Override annotation to override methods.
If you are new to annotations, read java annotations tutorial.
Java DOM Parser
Here is the java program that uses DOM Parser to read and parse XML file to get the list of Employee object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package com.journaldev.xml; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; 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; public class XMLReaderDOM { public static void main(String[] args) { String filePath = "employee.xml"; File xmlFile = new File(filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; try { dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nodeList = doc.getElementsByTagName("Employee"); //now XML is loaded as Document in memory, lets convert it to Object List List<Employee> empList = new ArrayList<Employee>(); for (int i = 0; i < nodeList.getLength(); i++) { empList.add(getEmployee(nodeList.item(i))); } //lets print Employee list information for (Employee emp : empList) { System.out.println(emp.toString()); } } catch (SAXException | ParserConfigurationException | IOException e1) { e1.printStackTrace(); } } private static Employee getEmployee(Node node) { //XMLReaderDOM domReader = new XMLReaderDOM(); Employee emp = new Employee(); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; emp.setName(getTagValue("name", element)); emp.setAge(Integer.parseInt(getTagValue("age", element))); emp.setGender(getTagValue("gender", element)); emp.setRole(getTagValue("role", element)); } return emp; } private static String getTagValue(String tag, Element element) { NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes(); Node node = (Node) nodeList.item(0); return node.getNodeValue(); } } |
Output of the above program is:
1 2 3 4 5 |
<span style="color: #008000;"><strong><code> Root element :Employees Employee:: Name=Pankaj Age=29 Gender=Male Role=Java Developer Employee:: Name=Lisa Age=35 Gender=Female Role=CSS Developer </code></strong></span> |
In real life, it’s not a bad idea to validate XML file before parsing it to objects, learn how to validate XML against XSD in java. That’s all about how to read xml file or parse xml file in java.
Reference: Official W3.org Doc