Step Past Times Pace Direct To Read Xml File Inward Coffee Using Sax Parser Example

Reading XML file inwards coffee using SAX Parser is niggling dissimilar than reading xml file inwards Java alongside DOM parser which nosotros had discussed inwards terminal article of this series. This tutorial is tin survive useful for those who are novel to the coffee basis together with got the requirement for read an xml file inwards java inwards their projection or assignment, primal characteristic of coffee is it provides built inwards degree together with object to handgrip everything which makes our work really easy. Basically this procedure of treatment XML file is known every bit parsing agency intermission downwards the whole string into small-scale pieces using the particular tokens.
Parsing tin survive done using ii ways:

  • Using DOM Parser
  • Using SAX Parser

Read XML file inwards Java Using SAX Parser Example

In DOM parser nosotros receive got seen that nosotros receive got to follow unproblematic iii steps:
Ø      Parse the XML file
Ø      Create the coffee object
Ø      Manipulate the object agency nosotros tin read that object or add together them to listing or any component subdivision nosotros desire nosotros tin do
But inwards SAX Parser its niggling chip different.

Reading XML file inwards coffee using SAX Parser Step By Step direct to Read XML file inwards Java Using SAX Parser ExampleSAX Parser: it’s an effect based parsing it contains default handler for treatment the events whenever SAX parser pareses the xml document together with it finds the Start tag “<” together with destination tag”>” it calls corresponding handler method.

Though at that spot are other ways too to larn information from xml file e.g. using XPATH inwards Java which is a linguistic communication similar SQL together with give selective information from xml file.


Sample Example of reading XML File – SAX Parser

Suppose nosotros receive got this sample XML file bank.xml which contains concern human relationship details of all accounts inwards a hypothetical bank:

<?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>



1.      Create the SAX parser together with parse the XML file:  In this mensuration nosotros volition accept i manufacturing works life lawsuit from SAXParserFactory to parse the xml  file this manufacturing works life lawsuit inwards turns  give us lawsuit of parser using the parse() method volition parse the Xml file.
2.      Event Handling: when Sax Parser starts the parsing whenever it founds the start or destination tag it volition invoke the corresponding effect treatment method which is public void startElement (…) together with world void destination Element (...).

3.       Register the events: The degree extends the Default Handler degree to head for callback events together with nosotros register this handler to sax Parser to notify us for telephone telephone dorsum event

Let catch coffee code for all these steps

To correspond information from our sample xml file nosotros involve i coffee domain object called Account:

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 inwards 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 principal method sets things upwardly 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 role the parser manufacturing works life to create a SAXParser object
              SAXParser sp = spfac.newSAXParser();

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

              //Finally, say the parser to parse the input together with notify the handler
              sp.parse("bank.xml", handler);
             
              handler.readList();

       }


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

       /*
        * Every fourth dimension the parser encounters the offset of a novel 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 destination of an element, it calls this method
        */
       public void endElement(String uri, String localName, String qName)
                     throws SAXException {

              if (qName.equalsIgnoreCase("Account")) {
                     // add together 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 inwards depository fiscal establishment '" + accList.size()  + "'.");
              Iterator<Account> it = accList.iterator();
              while (it.hasNext()) {
                     System.out.println(it.next().toString());
              }
       }
      
}

Output:
No of  the accounts inwards depository fiscal establishment '2'.
Account Details - Name:Jack Robinson, Type:saving, Id:1001, Age:10000.
Account Details - Name:Sony Corporation, Type:current, Id:1002, Age:1000000.
 



Advantage of SAX parser inwards Java:
It is faster than DOM parser because it volition non charge the XML document into the retentiveness .its an effect based.

Further Reading
Java Fundamentals: The Java Language
XML Fundamentals
RESTFul Services inwards Java using Jersey
Core Java, Volume II--Advanced Features
XSLT 2.0 together with 1.0 Foundations

Some other Tutorial yous may like




Sumber https://javarevisited.blogspot.com/

0 Response to "Step Past Times Pace Direct To Read Xml File Inward Coffee Using Sax Parser Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel