Read XML file using DOM parser

Read XML file using DOM parser

This demo will show how to read XML file using DOM parser . The Document Object Model provides APIs that let you create, read, modify, delete, and rearrange nodes. Also please be aware DOM load object tree to the heap memory before parsing it. For small XML document DOM is good choice but if you XML document is big then you probably look for SAX instead of DOM which does occupy space in memory. Next demo will show you how to read XMl file using SAX parser.

Below is ReadFileUsingDom.xml file which we are going to read using DOM parser:

<?xml version="1.0"?>  
 <Person id="1">  
</Persons> :


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;

public class ReadXmlFileUsingDomParser {

    public static void main(String[] args) {


    public static void readXmlFileUsingDomParser() {
	try {

	    File xmlFile = new File(
	    DocumentBuilderFactory documentFactory = DocumentBuilderFactory
	    DocumentBuilder documentBuilder = documentFactory
	    Document doc = documentBuilder.parse(xmlFile);

	    NodeList nodeList = doc

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

	    for (int temp = 0; temp < nodeList.getLength(); temp++) {
		Node node = nodeList.item(temp);

		System.out.println("\nElement type :"
			+ node.getNodeName());

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

		    Element person = (Element) node;

		    System.out.println("Person id : "
			    + person.getAttribute("id"));
		    System.out.println("First Name : "
			    + person.getElementsByTagName(
		    System.out.println("Last Name : "
			    + person.getElementsByTagName(
		    System.out.println("City : "
			    + person.getElementsByTagName(
		    System.out.println("State : "
			    + person.getElementsByTagName(
		    System.out.println("Email : "
			    + person.getElementsByTagName(
		    System.out.println("Phone : "
			    + person.getElementsByTagName(

	} catch (Exception exception) {




Read XML file using DOM parser

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *