Read XML File In JAVA using DOM – A Simple Tutorial

This tutorial is about reading xml file in a java program using the DOM (Document Object Model).

The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Objects under the DOM (also sometimes called “Elements”) may be specified and addressed according to the syntax and rules of the programming language used to manipulate them. The rules for programming and interacting with the DOM are specified in the DOM Application Programming Interface (API).

The sample XML document which the program will be reading is:

<?xml version="1.0"?>
<MyProduct>
  <Product>
    <ProductId>123</ProductId>
    <Description>Laptop</Description>
    <Price>$870</Price>
    <Quantity>1</Quantity>
    <Size>1</Size>
    <Total>$870</Total>
  </Product>
  <Product>
    <ProductId>124</ProductId>
   <Description>Monitor</Description>
   <Price>$200</Price>
   <Quantity>3</Quantity>
   <Size>4</Size>
   <Total>$600</Total>
   </Product>
</MyProduct>

The following is a java class that will read the XML file above.

package com.kushal.utils;
/**
 * Read XML File Using Java
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 21st July 2009
 */
import java.io.File;
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 ReadXMLFile {

public static void main(String argv[]) {

try {

File file = new File("c:/temp/MyProduct.xml");

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();

System.out.println("Root: "
+ doc.getDocumentElement().getNodeName() + "n");
NodeList nodeLst = doc.getElementsByTagName("Product");

for (int i = 0; i < nodeLst.getLength(); i++) {

Node myNode = nodeLst.item(i);

if (myNode.getNodeType() == Node.ELEMENT_NODE) {
/** Product ID* */
Element productElement = (Element) myNode;
NodeList productIdList = productElement
.getElementsByTagName("ProductId");
Element productIdElement = (Element) productIdList.item(0);
NodeList productId = productIdElement.getChildNodes();
System.out.println("Product ID : "
+ ((Node) productId.item(0)).getNodeValue());

/** Product Description* */
NodeList productDescriptionList = productElement
.getElementsByTagName("Description");
Element productDescriptionElement = (Element) productDescriptionList
.item(0);
NodeList productDescription = productDescriptionElement
.getChildNodes();
System.out.println("Product Description : "
+ ((Node) productDescription.item(0))
.getNodeValue());

/** Price* */
NodeList priceList = productElement
.getElementsByTagName("Price");
Element priceElement = (Element) priceList.item(0);
NodeList price = priceElement.getChildNodes();
System.out.println("Price : "
+ ((Node) price.item(0)).getNodeValue());

/** Quantity* */
NodeList quantityList = productElement
.getElementsByTagName("Quantity");
Element quantityElement = (Element) quantityList.item(0);
NodeList quantity = quantityElement.getChildNodes();
System.out.println("Quantity : "
+ ((Node) quantity.item(0)).getNodeValue());

/** Size* */
NodeList sizeList = productElement
.getElementsByTagName("Size");
Element sizeElement = (Element) sizeList.item(0);
NodeList size = sizeElement.getChildNodes();
System.out.println("Size : "
+ ((Node) size.item(0)).getNodeValue());

/** Total* */
NodeList totalList = productElement
.getElementsByTagName("Total");
Element totalElement = (Element) totalList.item(0);
NodeList total = totalElement.getChildNodes();
System.out.println("Total : "
+ ((Node) total.item(0)).getNodeValue());

System.out.println();

}

}
} catch (Exception e) {
e.printStackTrace();
}
}
}

===============================

Here is the output of this program.

Root: MyProduct
Product ID : 123
Product Description : Laptop
Price : $870
Quantity : 1
Size : 1
Total : $870

Product ID : 124
Product Description : Monitor
Price : $200
Quantity : 3
Size : 4
Total : $600


I received some comments on one of the posts about using POI to write to excel format. One of my blog users asked me how to read a XML document and then write to an EXCEL format.

  • You can use this post to see how the XML file is being read.
  • After reading the XML file you can store those values in a domain object, you can create any Product object with various attributes (id, description, price, quantity, size and total as field). You can store these objects in an array because there will be various products defined within a single XML file (two in above sample).
  • Once you have an array of objects, you can use my previous tutorial to write those values back to Excel Format

  1. All About Java Garbage Collection : Types, Algorithms, Advantages and Disadvantages
  2. Java Static Import Explained With Easy Example With Source Code
  3. SQL Example To Create Table On MySql DB
  4. Book Review – Drools JBoss Rules 5.X Developer’s Guide by Micahal Bali (Packt Publishing)
  5. List of valid @suppresswarning annotation parameters in Java for Eclipse and IBM RAD IDE
  6. Finding Java System Properties
  7. List of Major Java 7 Features – How java programming language has changed in JDK 7
  8. Date From Timestamp in Long format
  9. How to resolve – java.lang.VerifyError java.lang.SecurityException: Signers of org.junit.runner.Runner do not match signers of other classes in package
  10. Complete List Of Java Keywords
  11. List of 25 Plus Devices That Run On Java
  12. What is the difference between java and javaw?
  13. These 100 plus programming languages run on Java Virtual machine (List)
  14. Read XML File In JAVA using DOM – A Simple Tutorial
Tagged , , , , , , , , , , , , . Bookmark the permalink.

5 Responses to Read XML File In JAVA using DOM – A Simple Tutorial

  1. harry says:

    I need a tutorial on an exact opposite of this excellent article. That is I need to serialize Java Object to XML. Can you help me in that Kushal??? I wud appreciate it a lot.

    Thanks

  2. Jim says:

    Hey Kushal!
    This is very great and helpful, but I got another question about that. If I have an Element which hasn’t any values, I always get a NullpointerException. Do you have an Idea how to fix/catch that?

    Thank you!

  3. Mridula says:

    The advantage in Java is that there it is not necessary to take care of objects which are no longer used. Garbage collector takes care of these objects unlike C/C++ language where because of this issue the program terminates causing OutOfMemoryErrors.

  4. priya says:

    Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory.

Leave a Reply

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