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