read xml file in java

In this blog, I will show you how to read an XML file via DOM XML parser. DOM parser parses the entire XML document and loads it into memory; then models it in a “TREE” structure for easy traversal or manipulation.

In short, it turns a XML file into DOM or Tree structure, and you have to traverse a node by node to get what you want.

What is Node?
In the DOM, everything in an XML document is a node

Sample xml file


<?xml version="1.0"?>
<staff id="121">
<staff id="122">

DOM XML Parser Example

This example shows you how to get the node by “name”, and display the value.

package com.jft.seo;
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 ReadXMLFile {

public static void main(String argv[]) {

try {

File fXmlFile = new File("/home/anand/staff.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);


System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("staff");


for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

System.out.println("nCurrent Element :" + nNode.getNodeName());

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

System.out.println("Staff 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("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

} catch (Exception e) {


Output :

Root element :company

Current Element :staff
Id : 121
First Name : Anand
Last Name :Kushwaha
Nick Name : anand
Salary : 1000

Current Element :staff
Id : 122
First Name : Aman
Last Name : Goel
Nick Name : aman
Salary : 2000

Note :

DOM Parser is slow and consumes a lot of memory when it loads an XML document which contains a lot of data. Please consider SAX parser as solution for it, SAX is faster than DOM and use less memory.