Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Sunday, 2 June 2013

DOM xml parser - Read and Create xml file in Java using DOM

In previous discussion we came across different parser for xml in Java and a brief introduction of them. In today’s discussion we will see how to parse an xml in java using dom xml parser.

DOM so called (Domain object model) is the most commonly used and easiest implementation to parse an xml in java. DOM loads the xml tree into memory before parsing it, this is the reason we need to have a large heap size to eliminate memory exceptions. In case we have a large xml to parse it is better to use SAX instead of DOM, because loading a large xml in memory is not a good choice.

DOM is already a part of JDK, hence we don’t need to add any external jar to start with DOM.

Project Structure

Here is the overall project structure for today's discussion, we have two folders here 'createdFiles' contains xml that we have created from xml object and 'xmlFiles' contains an xml file that we will read using dom and show the contents on console. 'CreateXml.java' contains code to create xml file in java and 'ReadXml.java' contains code to read xml file in java dom.



How to read xml file using DOM parser in Java

Reading xml in java using DOM parser is simplest process compare to all other parsers.

Objective XML to parse

This is the sample xml file that we will read and show the content on console.
<?xml version="1.0"?>
<school>
 <student id="1">
  <firstname>ankush</firstname>
  <lastname>thakur</lastname>
  <email>beingjavaguy.gmail.com</email>
  <phone>7678767656</phone>
 </student>
 <student id="2">
  <firstname>aarti</firstname>
  <lastname>gupta</lastname>
  <email>aartigupta.gmail.com</email>
  <phone>9876546545</phone>
 </student>
</school>

ReadXml.java

Simple java class to parse the given xml file and print the data on console.
package com.beingjavaguys.core;

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 ReadXml {
 public void readXML() {
  try {

   File xmlFile = new File("xmlFiles/student.xml");
   DocumentBuilderFactory documentFactory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder documentBuilder = documentFactory
     .newDocumentBuilder();
   Document doc = documentBuilder.parse(xmlFile);

   doc.getDocumentElement().normalize();
   NodeList nodeList = doc.getElementsByTagName("student");

   System.out.println("Root element :"
     + doc.getDocumentElement().getNodeName());

   for (int temp = 0; temp < nodeList.getLength(); temp++) {
    Node node = nodeList.item(temp);

    System.out.println("\nElement type :" + node.getNodeName());

    if (node.getNodeType() == Node.ELEMENT_NODE) {

     Element student = (Element) node;

     System.out.println("Student id : "
       + student.getAttribute("id"));
     System.out.println("First Name : "
       + student.getElementsByTagName("firstname").item(0)
         .getTextContent());
     System.out.println("Last Name : "
       + student.getElementsByTagName("lastname").item(0)
         .getTextContent());
     System.out.println("Email Id : "
       + student.getElementsByTagName("email").item(0)
         .getTextContent());
     System.out.println("Phone No : "
       + student.getElementsByTagName("phone").item(0)
         .getTextContent());

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


Output data after reading xml




How to create a xml file using DOM parser in Java

Creating xml file in java using DOM parser is simplest process compare to all other parsers.

Objective XML to create

This is a sample xml file, we will try to create a xml file like this.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<school>
 <Student id="1">
  <firstname>ankush</firstname>
  <lastname>thakur</lastname>
  <email>beingjavaguy@gmail.com</email>
  <phone>8767675434</phone>
 </Student>
</school>

CreateXml.java

This is a simple java class where we have written code to create an xml file from java object. The code is quit simple and is explained with comments on every line.
package com.beingjavaguys.core;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CreateXml {
 public void createXML() {
  try {

   DocumentBuilderFactory documentFactory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder documentBuilder = documentFactory
     .newDocumentBuilder();

   // define root elements
   Document document = documentBuilder.newDocument();
   Element rootElement = document.createElement("school");
   document.appendChild(rootElement);

   // define school elements
   Element school = document.createElement("Student");
   rootElement.appendChild(school);

   // add attributes to school
   Attr attribute = document.createAttribute("id");
   attribute.setValue("1");
   school.setAttributeNode(attribute);

   // firstname elements
   Element firstname = document.createElement("firstname");
   firstname.appendChild(document.createTextNode("ankush"));
   school.appendChild(firstname);

   // lastname elements
   Element lastname = document.createElement("lastname");
   lastname.appendChild(document.createTextNode("thakur"));
   school.appendChild(lastname);

   // email elements
   Element email = document.createElement("email");
   email.appendChild(document.createTextNode("beingjavaguy@gmail.com"));
   school.appendChild(email);

   // phone elements
   Element phone = document.createElement("phone");
   phone.appendChild(document.createTextNode("8767675434"));
   school.appendChild(phone);

   // creating and writing to xml file
   TransformerFactory transformerFactory = TransformerFactory
     .newInstance();
   Transformer transformer = transformerFactory.newTransformer();
   DOMSource domSource = new DOMSource(document);
   StreamResult streamResult = new StreamResult(new File(
     "createdFiles/createFile.xml"));

   transformer.transform(domSource, streamResult);

   System.out.println("File saved to specified path!");

  } catch (ParserConfigurationException pce) {
   pce.printStackTrace();
  } catch (TransformerException tfe) {
   tfe.printStackTrace();
  }
 }
}



Implementation class code

This is simple java class with a main method, we have create two objects and called the required methods simply to see the output.

Dom Implementation.java

package com.beingjavaguys.core;

public class DomImplementation {
  public static void main(String args[]){
   
   // parsing xml
   ReadXml readXml = new ReadXml();
   readXml.readXML();
   
   // create xml file
   CreateXml createXml = new CreateXml();
   createXml.createXML();
  }
}


In this particular blog we cam across 'How to read xml file in java using DOM' and 'How to create a xml file in Java using DOM'. In upcoming blogs we will coma across more about java xml parsers and their implementation. Read more about XML & JSON under SAX & JDOM2 & XML parser in Java JSON, and JAXB - Marshalling & Unmarshalling in Java categories.









Thanks for reading !
Being Java Guys Team

Download "Read and Create XML in Java using DOM parser" from "SkyDrive"





8 comments:

  1. It's really good, thanks !

    ReplyDelete
  2. Is it domain object model or Document object model.

    ReplyDelete
  3. DOM Stands for 'Document Object Model' not 'domain object model'

    ReplyDelete
  4. thanks ,it was clear and straight .Thanks!!

    ReplyDelete
  5. How to upload a xml file instruts2 and read to store the Database pla help me

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft