Wednesday, May 27, 2015

Parsing an XML document using SAX Parser

Aim:
            To create simple SAX parser to parse XML document

Algorithm:

  1. Create a Sax parser and parse the xml
  2. In the event handler create the employee object
  3. Print out the data

Program:

SAXParserExample.java

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

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 SAXParserExample extends DefaultHandler{

            List myEmpls;
           
            private String tempVal;
           
            //to maintain context
            private Employee tempEmp;
           
           
            public SAXParserExample(){
                        myEmpls = new ArrayList();
            }
           
            public void runExample() {
                        parseDocument();
                        printData();
            }

            private void parseDocument() {
                       
                        //get a factory
                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        try {
                       
                                    //get a new instance of parser
                                    SAXParser sp = spf.newSAXParser();
                                   
                                    //parse the file and also register this class for call backs
                                    sp.parse("employees.xml", this);
                                   
                        }catch(SAXException se) {
                                    se.printStackTrace();
                        }catch(ParserConfigurationException pce) {
                                    pce.printStackTrace();
                        }catch (IOException ie) {
                                    ie.printStackTrace();
                        }
            }

            /**
             * Iterate through the list and print
             * the contents
             */
            private void printData(){
                       
                        System.out.println("No of Employees '" + myEmpls.size() + "'.");
                       
                        Iterator it = myEmpls.iterator();
                        while(it.hasNext()) {
                                    System.out.println(it.next().toString());
                        }
            }
           

            //Event Handlers
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                        //reset
                        tempVal = "";
                        if(qName.equalsIgnoreCase("Employee")) {
                                    //create a new instance of employee
                                    tempEmp = new Employee();
                                    tempEmp.setType(attributes.getValue("type"));
                        }
            }
           

            public void characters(char[] ch, int start, int length) throws SAXException {
                        tempVal = new String(ch,start,length);
            }
           
            public void endElement(String uri, String localName, String qName) throws SAXException {

                        if(qName.equalsIgnoreCase("Employee")) {
                                    //add it to the list
                                    myEmpls.add(tempEmp);
                                   
                        }else if (qName.equalsIgnoreCase("Name")) {
                                    tempEmp.setName(tempVal);
                        }else if (qName.equalsIgnoreCase("Id")) {
                                    tempEmp.setId(Integer.parseInt(tempVal));
                        }else if (qName.equalsIgnoreCase("Age")) {
                                    tempEmp.setAge(Integer.parseInt(tempVal));
                        }
                       
            }
           
            public static void main(String[] args){
                        SAXParserExample spe = new SAXParserExample();
                        spe.runExample();
            }
           
}


Employee.java



public class Employee {

            private String name;

            private int age;
           
            private int id;

            private String type;
           
            public Employee(){
                       
            }
           
            public Employee(String name, int id, int age,String type) {
                        this.name = name;
                        this.age = age;
                        this.id  = id;
                        this.type = type;
                       
            }
            public int getAge() {
                        return age;
            }

            public void setAge(int age) {
                        this.age = age;
            }

            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("Employee Details - ");
                        sb.append("Name:" + getName());
                        sb.append(", ");
                        sb.append("Type:" + getType());
                        sb.append(", ");
                        sb.append("Id:" + getId());
                        sb.append(", ");
                        sb.append("Age:" + getAge());
                        sb.append(".");
                       
                        return sb.toString();
            }
}

Employees.xml

<?xml version="1.0" encoding="UTF-8" ?>
<Personnel>
<Employee type="permanent">
  <Name>Seagull</Name>
  <Id>3674</Id>
  <Age>34</Age>
  </Employee>
<Employee type="contract">
  <Name>Robin</Name>
  <Id>3675</Id>
  <Age>25</Age>
  </Employee>
<Employee type="permanent">
  <Name>Crow</Name>
  <Id>3676</Id>
  <Age>28</Age>
</Employee>
</Personnel>


No comments:

Post a Comment