DOM: How to read XML File in Java

Connect with

Oracle Java
In this post, I tried to demonstrate, how to read XML for either getting its content of element or name of element or comment in the XML or attribute value of any element by using DOM (Document Object Model) parser in java. In your professional life, while developing, you must encountererd most of the time to read of XML either configuration file or any other XML.

1. Overview of DOM(Document Object Model)

To parse XML in DOM (Document Object Model), it’s loads the entire XML document 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.

2. 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
    

3. 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

4. When DOM parser is preferable?

DOM Parser is slow if the size of XML is large and consumes a lot of memory when it loads an XML document which contains a lot of data. If you have a large file of XML, then it’s not preferable to parse using DOM, as you know this consumes a lot of memory. If you have a light configuration XML file to load while initialization or any other purpose then it works very faster to parse using via DOM parser. I strongly recommend, SAX (Simple API for XML) parser as a solution for it parsing large XML content/file, SAX is faster than DOM and uses less memory. DOM is recommended especially when the size of XML is small.

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


Connect with

Leave a Comment

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