How to Parse XML file using DOM Parser?

In this tutorial I will write a simple example program for parsing a XML file using the DOM parser. DOM parser reads the entire XML file and loads into the memory. It forms a tree structure in the memory and returns the element details when queried. It is the faster when comparing to the SAX parser. But, it consumes huge memory when the XML file is large in size. DOM parser is very good choice when the XML file size is relatively small and memory is not an issue for the performance.

If the XML is huge, choose SAX parser which will be faster and consumes less memory.


<?xml version="1.0"?>
	<employee id="001">
	<employee id="002">


import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class JavaDOMParser {
	public static void main(String argv[]) {
		try {
			File xmlFilePath = new File("employees.xml");
			DocumentBuilderFactory factory = DocumentBuilderFactory
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(xmlFilePath);
			System.out.println("Root element :"
					+ doc.getDocumentElement().getNodeName());
			NodeList nList = doc.getElementsByTagName("employee");
			for (int temp = 0; temp < nList.getLength(); temp++) {
				Node nNode = nList.item(temp);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element) nNode;
					System.out.println("Employee Id : "
							+ eElement.getAttribute("id"));
					System.out.println("First Name : "
							+ eElement.getElementsByTagName("firstname")
					System.out.println("Last Name : "
							+ eElement.getElementsByTagName("lastname").item(0)
		} catch (Exception e) {

Output for this program will be:

Root element :company
Employee Id : 001
First Name : Krishna
Last Name : Srinivasn
Employee Id : 002
First Name : Muthu
Last Name : Kumar



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.