Skip to main content

XML Parsing Dengan Java Bag. I (Menggunakan DOM Parser)

Dulu sewaktu kuliah saya pernah pernah berpikir untuk membuat suatu applikasi yang dapat membaca dan menulis file configurasinya sendiri. lalu saya menggunakan text file sebagai media penyimpan konfigurasi.... seiring perkembangan dan jam terbang bertambah sayapun sempat terpikir untuk mengganti text file yang digunakan menjadi XML (Extensible Markup Language) dimana dokumen ini memiliki keunggulan yang sangat banyak. tidak hanya sebagai media penyimpanan konfigurasi, ternyata XML juga banyak digunakan sebagai media penyimpanan data. seperti contoh berikut ini.


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

Dokumen XML diatas menjabarkan tentang struktur data kepegawaian. lalu apa kegunaannya pada aplikasi? dan bagaimana caranya?

Oke, pada posting saya berikut ini kita akan membuat suatu aplikasi yang memiliki fungsi untuk membaca(parse) data-data tersebut kedalam applikasi.

Kira-kira output dari applikasi ini adalah:

Employee Details - Name:Seagull, Type:permanent, Id:3674, Age:34.
Employee Details - Name:Robin, Type:contract, Id:3675, Age:25.
Employee Details - Name:Crow, Type:permanent, Id:3676, Age:28.

Ada 2 cara dalam membaca dokumen XML, 1) Menggunakan DOM(Document Object Modeling) Parser, 2) Menggunakan SAX (Simple API for XML). Pada posting kali ini kita akan mencoba menggunakan DOM Parser.

Ada beberapa langkah yang harus dilakukan:
  1. Buka File XML
  2. Parse XML
  3. Petakan hasil parse kedalam beans
  4. tampilkan beans
berikut cara membuka file XML kedalam bentuk Object

private void parseXmlFile(){
  //get the factory
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

  try {

   //Using factory get an instance of document builder
   DocumentBuilder db = dbf.newDocumentBuilder();

   //parse using builder to get DOM representation of the XML file
   dom = db.parse("employees.xml");


  }catch(ParserConfigurationException pce) {
   pce.printStackTrace();
  }catch(SAXException se) {
   se.printStackTrace();
  }catch(IOException ioe) {
   ioe.printStackTrace();
  }
 }

Setelah object dari dokumen XML telah dibuka maka tahap selanjutnya adalah membuat function untuk memparsing object dari dokumen XML tadi. berikut adalah function untuk mem-parsing Object document XML

private void parseDocument(){
  //get the root element
  Element docEle = dom.getDocumentElement();

  //get a nodelist of 
 elements
  NodeList nl = docEle.getElementsByTagName("Employee");
  if(nl != null && nl.getLength() > 0) {
   for(int i = 0 ; i < nl.getLength();i++) {

    //get the employee element
    Element el = (Element)nl.item(i);

    //get the Employee object
    Employee e = getEmployee(el);

    //add it to list
    myEmpls.add(e);
   }
  }
 }

dalam proses parsing diatas kita akan menemukan elemen-elemen file XML yang kemudian elemen-elemen tersebut akan kita petakan kedalam sebuah atau sekumpulan dari bean, sebut saja Employee beans. berikut adalah function untuk memetakan elemen-elemen dari dokumen XML kedalam Employee beans.

private Employee getEmployee(Element empEl) {

  //for each  element get text or int values of
  //name ,id, age and name
  String name = getTextValue(empEl,"Name");
  int id = getIntValue(empEl,"Id");
  int age = getIntValue(empEl,"Age");

  String type = empEl.getAttribute("type");

  //Create a new Employee with the value read from the xml nodes
  Employee e = new Employee(name,id,age,type);

  return e;
 }


 /**
  * I take a xml element and the tag name, look for the tag and get
  * the text content
  * i.e for John xml snippet if
  * the Element points to employee node and tagName is 'name' I will return John
  */
 private String getTextValue(Element ele, String tagName) {
  String textVal = null;
  NodeList nl = ele.getElementsByTagName(tagName);
  if(nl != null && nl.getLength() > 0) {
   Element el = (Element)nl.item(0);
   textVal = el.getFirstChild().getNodeValue();
  }

  return textVal;
 }


 /**
  * Calls getTextValue and returns a int value
  */
 private int getIntValue(Element ele, String tagName) {
  //in production application you would catch the exception
  return Integer.parseInt(getTextValue(ele,tagName));
 }

Setelah kita mendapatkan list of Employee beans, yang proses selanjutnya adalah mencetak data-data didalam list ke output.

private void printData(){

  System.out.println("No of Employees '" + myEmpls.size() + "'.");

  Iterator it = myEmpls.iterator();
  while(it.hasNext()) {
   System.out.println(it.next().toString());
  }
 }


Selesai sudah kita membaca(parse) sebuah dokumen XML dengan mengunakan DOM Parser. untuk teknik pembacaan dokumen XML menggunakan SAX akan dibahas pada posting selanjutnya.

source

Comments

Anonymous said…
Another XML parser is called vtd-xml, it is better than DOM and SAX

http://vtd-xml.sf.net
shido said…
thank you... next time i'll review it.. btw... thanks for visiting...
HERLoct_HENT said…
@_@ tu cara paling normal buat parsing XML di Java aniki??? walah, ribet...

Coba liat E4X (Ecmascript for XML) dah, tu baru parsing/creating XML paling mantap... sayang blm nemu penerapannya di Java :((
shido said…
ECMA itu standar bahasa ala javascript/actionscript bukan? dia mah ECMAscript itu rata-rata client base bro, di alamat ini http://vtd-xml.sf.net ada parser xml mudah

Popular posts from this blog

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

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