DOM XML parser to parse XML file in java

The DOM refers to Document Object Model. The DOM parses the XML file, creates the DOM objects and loads it into the memory in the tree structure.
Note: DOM is simple and easy to use but it consume lots of memory and slow.
The XML refers to the EXtensible Markup Language which is used to store and transport the data. XML not provides any predefined tags. We have to define our own tags. Every opening XML tag must have a closing tag. XML tags are case sensitive and must be completely nested.

Steps to read a XML file:

1. Create a Document with DocumentBuilder class.
2. Fetch the root element.
3. Process the child elements.
4. Process the attributes.


<?xml version="1.0"?>
<student rollno="1">
<student rollno="2">
<student rollno="3">
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
* This class is used to parse XML document using DOM parser.
* @author javawithease

public class DOMParserReadTest {
public static void main(String args[]){
try {
//File Path
String filePath = "D:\\StudentTest.xml";
//Read XML file.
File inputFile = new File(filePath);
//Create DocumentBuilderFactory object.
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
//Get DocumentBuilder object.
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
//Parse XML file.
Document document = dBuilder.parse(inputFile);
//Print root element.
System.out.println("Root element:"
+ document.getDocumentElement().getNodeName());
//Get element list.
NodeList nodeList =
//Process element list.
for (int temp = 0; temp < nodeList.getLength(); temp++) {
Node nNode = nodeList.item(temp);
System.out.println("\nCurrent Element:"
+ nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Roll no: "
+ eElement.getAttribute("rollno"));
System.out.println("First Name: "
+ eElement.getElementsByTagName("firstname")
System.out.println("Last Name: "
+ eElement.getElementsByTagName("lastname")
System.out.println("Marks: "
+ eElement.getElementsByTagName("marks")
} catch (Exception e) {


Root element:class
Current Element:student
Roll no: 1
First Name: Swati
Last Name: Aneja
Marks: 80
Current Element:student
Roll no: 2
First Name: Prabhjot
Last Name: Kaur
Marks: 70
Current Element:student
Roll no: 3
First Name: Nidhi
Last Name: Gupta
Marks: 75

No comments: