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.

employee.xml

<?xml version="1.0"?>
<company>
	<employee id="001">
		<firstname>Krishna</firstname>
		<lastname>Srinivasn</lastname>
	</employee>
	<employee id="002">
		<firstname>Muthu</firstname>
		<lastname>Kumar</lastname>
	</employee>
</company>

JavaDOMParser.java

package javabeat.net.xml;

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;
import java.io.File;

public class JavaDOMParser {
	public static void main(String argv[]) {
		try {
			File xmlFilePath = new File("employees.xml");
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(xmlFilePath);
			doc.getDocumentElement().normalize();
			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")
									.item(0).getTextContent());
					System.out.println("Last Name : "
							+ eElement.getElementsByTagName("lastname").item(0)
									.getTextContent());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

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

Comments

comments

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.

Speak Your Mind

*