Read XML File DOM parser in Java

Connect with

Read XML File DOM parser in JavaLearn how to Read XML File DOM parser in Java. Read XML file using DOM parser in Java. Java example to read XML using DOM parser in Java.

1. Read XML file DOM parser in 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, you must encounter most of the time to read XML either configuration file or any other XML.
To parse XML in DOM (Document Object Model) in Java programming language, 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

In this section you learn how to read XML file using DOM parser in Java example.

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";

 /**
  * How to read XML file DOM parser in java
  */
 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 the 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:
The output of read xml file DOM parser in java as follows:

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 little slow if the size of XML is large and DOM parser consumes a lot of memory when it loads an XML document that 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.

5. Related Post on XML Parser

In order to understand the difference Parsers eitehr DOM Parser and SAX parser, you have to understand each one of the parsers. For this you can visit.

6. Reference

Read XML file DOM parser in Java
I hope you enjoyed this post about how to read XML file DOM parser in java, visit Core Java tutorial for more blog post.

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 *