DOM: How to read XML File in Java

Connect with

Oracle Java
In this post, I tried to demonstrate, how to read xml content by using DOM (Document Object Model) parser in java. In your project life you encountererd most of the time to read xml of either configuration file or any another xml.

To parse XML in DOM (DOcument Object Model), its loads entire XML docuement into memory then models it in a ‘Tree’ like structure for easy traversal or manipulation. And you have to traverse node by node to get the node content , node comment, node name etc.

There is no dependency , it means no any third party .jar file required put in classpath of the project to parse xml document in java using DOM. .jar is already in J2SE.

1. Sample XML file to parse in java (DOM Parser)

put the following xml content in the book.xml in side the project /docs/ folder. And write you code java using dom parser.

File: ./docs/book.xml



    
	  Java Webservice Up And Running
	  Bill Burk
	  0123456789
    
    
   	  SCJP6
	  Kaithy Sierra and Bert Bates
	  9876543210
    

2. Java code to read XML using DOM parser

package com.mysoftkey.jws.dom.ex1;

import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMReadingExample {

 // put the content in project docs folder
 private final static String fileName = "./docs/book.xml";

 /**
  * @param args
  */
 public static void main(String[] args) {
  DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = null;
  try {
   // build DOM builder factory to craete document.
   builder = builderFactory.newDocumentBuilder();

   // parse XML files into DOM objects
   Document document = builder.parse(new File(fileName));

   // get Root Element for xml tree
   Element rootElement = document.getDocumentElement();

   // get childrens can be elements, comments, processing instructions,
   // characters etc,
   NodeList nodes = rootElement.getChildNodes();
   for (int i = 0; i < nodes.getLength(); i++) {
    Node node = nodes.item(i);

    // if node is an Element then process accordingly.
    if (node instanceof Element) {
     Element book = (Element) node;
     String title = book.getElementsByTagName("title").item(0).getTextContent();
     String author = book.getElementsByTagName("author").item(0).getTextContent();
     String isbn = book.getElementsByTagName("ISBN").item(0).getTextContent();
     String id = book.getAttribute("id");
     author = getElementValueByName(book, "author");
     System.out.println("id: " + id + "  , title: " + title + ", author: " + author + " , isbn:" + isbn);
     String nodeValue = book.getTextContent();

     // Attr attribute = child.getAttributeNode("id");
    }
   }
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 /**
  * this function is used to read Node by element name using DOM parser in java.
  * 
  * @param element
  * @param name
  * @return
  */
 public static String getElementValueByName(Element element, String name) {
  String value = null;
  if (name != null) {
   NodeList nodeList = element.getElementsByTagName(name);
   for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);
    if (node != null) {
     value = node.getTextContent();
    }
   }
  }
  return value;
 }

}

Output of the program:

id: 1  , title: Java Webservice Up And Running, author: Bill Burk , isbn:0123456789
id: 2  , title: SCJP6, author: Kaithy Sierra and Bert Bates , isbn:9876543210

3. When DOM parser preferrable

DOM Parser is slow and consumes a lot of memory when it loads an XML document which contains a lot of data. If you have a larg file of XML , then its not preferrable to parse using DOM , as you know this consume lot of memory. If you have light configuration xml file to load while initialization or any another purpose then its ok to parse using via DOM parser. I strongly recommend , SAX (Simple API for XML) parser as solution for it parsing large XML content/file, SAX is faster than DOM and use less memory.

Your comment is welcome to improve this post. Happy Learning 🙂


Connect with

Leave a Reply

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