Monday 25 November 2013

Reading the xml File and Loading into the database

There are so many ways to read the xml file. In that 2 ways here i am going to explain. i.e.
1. Reading the xml files using DOM Parser
2. Reading the xml files using SAX Parser







Difference Between DOM and SAX Parsers:


Parses node by node Stores the entire XML document into memory before processing
Doesn’t store the XML in memory Occupies more memory
We cant insert or delete a node We can insert or delete nodes
Top to bottom traversing Traverse in any direction.
SAX is an event based parser DOM is a tree model parser
SAX is a Simple API for XML Document Object Model (DOM) API
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
 
doesn’t preserve comments preserves comments
SAX generally runs a little faster than DOM SAX generally runs a little faster than DO


SAX Parser:

  •     It’s an event based parsing it contains default handler for handling the events.
  •     SAX parser pareses the xml document and it finds the Start tag “<” and end tag”>” it calls                 corresponding handler method.
  •     Sample Example of reading XML File – SAX Parser






Advantage:
  • It is faster than DOM parser because it will not load the XML document into the memory .
  • Sax is an event based parser.





sample.xml:


<?xml version="1.0" encoding="UTF-8"?>
<Bank>
      <Account type="saving">
            <Id>1001</Id>
            <Name>Jack Robinson</Name>
            <Amt>10000</Amt>
      </Account>
      <Account type="current">
            <Id>1002</Id>
            <Name>Sony Corporation</Name>
            <Amt>1000000</Amt>
      </Account>
</Bank>


SampleVO.java

package parser;

public class Account {

       private String name;
       private int id;
       private int amt;
       private String type;

       public Account() {
       }

       public Account(String name, int id, int amt, String type) {
              this.name = name;
              this.amt = amt;
              this.id = id;
              this.type = type;
       }

       public int getAmt() {
              return amt;
       }

       public void setAmt(int amt) {
              this.amt = amt;
       }

       public int getId() {
              return id;
       }

       public void setId(int id) {
              this.id = id;
       }

       public String getName() {
              return name;
       }

       public void setName(String name) {
              this.name = name;
       }

       public String getType() {
              return type;
       }

       public void setType(String type) {
              this.type = type;
       }

       public String toString() {
              StringBuffer sb = new StringBuffer();
              sb.append("Account Details - ");
              sb.append("Name:" + getName());
              sb.append(", ");
              sb.append("Type:" + getType());
              sb.append(", ");
              sb.append("Id:" + getId());
              sb.append(", ");
              sb.append("Age:" + getAmt());
              sb.append(".");

              return sb.toString();
       }
}




Sample Code for implementing SAX parser in Java

ReadXMLFileUsingSaxparser.java:




package parser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXMLFileUsingSaxparser extends DefaultHandler {

       private Account acct;
       private String temp;
       private ArrayList<Account> accList = new ArrayList<Account>();

       /** The main method sets things up for parsing */
       public static void main(String[] args) throws IOException, SAXException,
                     ParserConfigurationException {
            
              //Create a "parser factory" for creating SAX parsers
              SAXParserFactory spfac = SAXParserFactory.newInstance();

              //Now use the parser factory to create a SAXParser object
              SAXParser sp = spfac.newSAXParser();

              //Create an instance of this class; it defines all the handler methods
              ReadXMLFileUsingSaxparser handler = new ReadXMLFileUsingSaxparser();

              //Finally, tell the parser to parse the input and notify the handler
              sp.parse("bank.xml", handler);
            
              handler.readList();

       }


       /*
        * When the parser encounters plain text (not XML elements),
        * it calls(this method, which accumulates them in a string buffer
        */
       public void characters(char[] buffer, int start, int length) {
              temp = new String(buffer, start, length);
       }
     

       /*
        * Every time the parser encounters the beginning of a new element,
        * it calls this method, which resets the string buffer
        */
       public void startElement(String uri, String localName,
                     String qName, Attributes attributes) throws SAXException {
              temp = "";
              if (qName.equalsIgnoreCase("Account")) {
                     acct = new Account();
                     acct.setType(attributes.getValue("type"));

              }
       }

       /*
        * When the parser encounters the end of an element, it calls this method
        */
       public void endElement(String uri, String localName, String qName)
                     throws SAXException {

              if (qName.equalsIgnoreCase("Account")) {
                     // add it to the list
                     accList.add(acct);

              } else if (qName.equalsIgnoreCase("Name")) {
                     acct.setName(temp);
              } else if (qName.equalsIgnoreCase("Id")) {
                     acct.setId(Integer.parseInt(temp));
              } else if (qName.equalsIgnoreCase("Amt")) {
                     acct.setAmt(Integer.parseInt(temp));
              }

       }

       private void readList() {
              System.out.println("No of  the accounts in bank '" + accList.size()  + "'.");
              Iterator<Account> it = accList.iterator();
              while (it.hasNext()) {
                     System.out.println(it.next().toString());
              }
       }
     
}

Output:

No of  the accounts in bank '2'.
Account Details - Name:Jack Robinson, Type:saving, Id:1001, Age:10000.
Account Details - Name:Sony Corporation, Type:current, Id:1002, Age:1000000.





No comments:

Post a Comment

SpringBoot

SpringBoot SpringBoot Application :  Pros & Cons :  SpringBoot Application creation using spring.io :  SpringBoot Application Annotation...