Thursday, 26 January 2012

Easy way for XML parsing using JAVA

HI,
In this article we will go through a very common scenario to parse the XML file and make the data persistent.

Making the data persistent means storing the data into the database,by means of any coding language such as java.Various tools such as Apache xerces,dom4j,neopull etc..are availbale to parse the XML file.
But it is very important to to understand the basic concept of parsing first and  once when you get the basic idea, you can jump for bigger step..parsing using frameworks..

We will start with the basic stuff

Why XML is  popular??

And the answer is very obvious,and straight froward.It is very simple and convenient.
It is simple in the sense it is highly structured and anyone with little knowledge of HTML can read and understand the contents of the XML file.And convenient because the XML data can be manipulated according to our need.

Why Parsing is necessary??

XML is just a carrier of the data from one platform to another.We need some sort of technique through which we can extract the XML data and make that data visible to our application.This is called PARSING.


Which Parser to use and when??

Selecting the perfect parser for our need is the first step that we all should consider.Among the most popular parser DOM and SAX are used.Both are used for a diffrent purpose.

DOM(Document Object Model): As the name suggest this is the dynamic approach of parsing.It defines the objects and method interface through which you can parse the XML document.In simple words if you have lot of memory available for running the code the you can choose this approach because DOM treats the XML file as whole.It will parse your whole document atonce.

SAX(Simple API for XML):It is a event based model.It treats the XML file piece by piece.So if you have limited memory the you can select this option.It is faster than DOM and in most of the cases SAX is preffered over DOM.

Enough for the introduction now we will move onto the code part.

First of all we will define a XML file:

employee.xml

<company>
     <employee>
            <fname>nikhil</fname>
            <lname>joshi</lname>
            <id>1000</id>
    </employee>

</company>




You need to import following packages:

/*
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

*/

private void parseXml(){
//get the Document factory

  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

try {

//get an instance of document builder

   DocumentBuilder db = dbf.newDocumentBuilder();

//parse using builder to get DOM representation of the XML file

   dom = db.parse("employee.xml");

//get the root element

  Element docEle = dom.getDocumentElement();

// get the node list.here we have to give tag name
//employee in our case.

NodeList n = docEle.getElementsByTagName("employee");

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

                    Node empnode =  n.item(s);
                   if(emp.getNodeType() == Node.ELEMENT_NODE)
                            {
                  
                    Element empele = (Element) empnode;

                     //get first tag

                    NodeList fnamelist  =  empele.getElementsByTagName("fname");
                    Element firstNameElement = (Element)fnamelist.item(0);
                    NodeList textfirstList = firstNameElement.getChildNodes();
 System.out.println("First Name : " ((Node)textfirstlist.item(0)).getNodeValue().trim());             


                   //get second tag

                   NodeList lnamelist = empele.getElementsByTagName("lname");
                   Element lastNameElement = (Element)lnamelist.item(0);
                  NodeList textlastList = lastNameElement.getChildNodes();
 System.out.println("Last Name : " ((Node)textlastList.item(0)).getNodeValue().trim());

                  
                     //get second tag

                  NodeList idlist = empele.getElementsByTagName("id");
                   Element idElement = (Element)idlist.item(0);
                   NodeList textidList = idElement.getChildNodes();
 System.out.println("ID : " ((Node)textidList.item(0)).getNodeValue().trim());

                    }//end of if block
}//end of for block

  }//end of try
catch (SAXParseException err) {
        err.printStackTrace();
       }
catch(SAXException e){
e.printStackTrace();
}
catch (Throwable t) {
        t.printStackTrace ();
        }
}


Hope this will help you.All the Best.

5 comments:

  1. nice work done:)thanks it's really helpful for me.

    ReplyDelete
  2. This is very useful information :)

    ReplyDelete
  3. Came across nice and short content on SAPUI5 in You tube. You get clarity on what ui5 and fiori is all about. This could be the right place to start learning sapui5. You tube link for ui5 videos
    https://www.youtube.com/channel/UC_mN5oWZJOpTuzKzgp_QPjg

    ReplyDelete
  4. Very good article and useful post. freshers also can easily understand thank you for sharing this article with us. Know more about SAPUI5 Training

    ReplyDelete