Skip to main content

Parsing XML dengan java SAX Parser

Melanjutkan dari post saya tentang parsing XML dengan Java, pada entri sebelumnya teknik parsing yang digunakan dengan menggunakan DOM Parser. pada entri kali ini saya akan membahas bagaimana cara untuk mem-parsing XML dengan SAX parser.


pada entri kali ini kita tetap menggunakan XML dengan struktur yang sama dengan entri sebelumnya.



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

pembacaan xml dengan SAX Parser sangat berbeda dengan pembacaan XML dengan cara DOM (Document Object Modeling), karena SAX Parser melakukan pembacaan melalui sebuah Handler. Pada Handler inilah semua tag yang menurut kita berarti akan diproses...


pada baris program dibawah ini class SAXParserExample merupakan class turunan dari DefaultHandler, dimana class DefaultHandler adalah sebuah abstract class yang mengharuskan class turunannya untuk melakukan overrides terhadap method-method berikut:

  • public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
  • public void characters(char[] ch, int start, int length) throws SAXException
  • public void endElement(String uri, String localName, String qName) throws SAXException

Berikut adalah penjelasan fungsi dari ketiga method tersebut secara simple:
  1. method startElement merupakan entry point bagi parser didalam melakukan pembacaan tag. pada method ini kita dapat melakukan seleksi terhadap tag-tag apa yang akan kita proses maupun dengan melakukan pengecekan pada parameter qName
  2. method characters digunakan untuk membaca tag body, jika tag merupakan tag yang tidak mempunyai body maka method ini tidak akan memberikan parameter apapun alias kosong.
  3. method endElement merupakan method yang diakses oleh parser ketika parser menemukan penutup dari tag yang sebelumnya dibaca oleh startElement
Berikut adalah source code lengkapnya

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();
}

}

membingungkan? pada awalnya, pengunaan SAX Parser pasti sangat membingunkan, namun penggunaan SAX Parser memberikan kita keleluasaan didalam melakukan penterjemahan terhadap dokumen XML yang akan kita.

Comments

Popular posts from this blog

Penjualan PSVita Menurun Dijepang

PlayStation 3, sebuah konsol game yang diusung raksasa elekronik asal negeri sakura ini sedang mengalami masa-masa menyenangkan dilihat dari penjualannya yang terus meningkat dibeberapa minggu dibulan ini. Namun hal ini tidak terjadi pada konsol game portabel PSVita yang sama-sama buatan Sony. Penjualan PSVita dalam beberapa minggu ini terus mengalami penurunan yang membuat kondisi ini menjadi suatu berita baik sekaligus buruk bagi Sony. Hal ini diperkuat oleh grafik penjualan yang dibuat oleh beberapa media Jepang yang isinya mencakup tentang penjualan kedua konsol game tersebut dari tanggal 27 Februari hingga 4 Maret. Dalam grafik tersebut menunjukan prestasi PlayStation 3 sebagai pemenang besar di segmen perangkat keras dengan penjualan sebesar 65,116 unit pada kurun waktu tersebut. Sony juga diindikasikan telah berhasil menjual PS3 hampir 2.5x lebih banyak dari minggu sebelumnya... Penjualan hardware yang kuat ini oleh beberapa media jepang dipicu oleh peluncuran piranti...

The Future Of Computing is Ubuntu Phone

As we are know, in the beginning of January 2013. Canonical announce their new project called Ubuntu Phone. From the beginning Ubuntu was just another Linux distro,  but now Canonical driving Ubuntu far beyond its beginnings as just another Linux distro into an Operating System that works on  television and even being  an android and iPhone competitor, Ubuntu is skating to where they puck is going to be. But, which such a bold move, there are significant obstacles to overcome. The soon to be released Ubuntu Phone is paving the way that all smart phones will eventually go. Back to the late  1943 where  computers were gigantic, filling rooms and requiring constant care and maintenance. Over time, the components required to build the computers become smaller and cheaper, till eventually it was possible to put one on your desk until the laptop computer, a smaller, more portable, but just as powerful machine was made and make it nearly obsolete. And then, com...

Fix windows's MBR without installation Disk using linux!!!

Bismillahirohmanirrohim... Assalamualaykum, When I was trying out new ubuntu 12.04. The installation progress went wrong and then freeze. After a couple of minutes the progress still the same. Before installing 12.04, my system was running ubuntu 11.04 dualboot (windows 7). Within my experience, when the installation of linux went wrong, the next step is recovering windows MBR using installation disk. But alas, my DVD-RW was busted long time ago and I haven't fix it or intent to fix it. The only thing I have is Ubuntu USB Thumbdrive. After googling awhile I found out to recover windows MBR using Ubuntu thumbdrive. First, make sure syslinux packages are installed or update to the latest version using this command $ sudo apt-get install syslinux When syslinux packages installed, enter this command to write windows MBR image into the harddrive's boot sector(/dev/sda) $ sudo dd if=/usr/lib/syslinux/mbr.bin of=/dev/sda Next thing to do is restart your PC using unity or usi...