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

It's been a while...

It's been a while since my last blog entry. Maybe this time I'll try to write something into this blog. Something about computer and programming related or something other than that. And for all my reader (is there any?), I want to tell you my appreciation and my best regards... Thank You..

Throwing The Sun Tzu Baby Out With The InfoSec Bathwater

Steve Tornio and Brian Martin just published a  5,000 word rant  against anyone who dares utter the name Sun Tzu in connection with information security. According to Tornio and Martin, Sun Tzu – the principal strategic authority who’s seminal work has served to guide China’s military and civilian leadership for 2500 years, is “ not relevant to modern day InfoSec ” because  “information security is not warfare (leaving aside actual warfare, of course” . That’s a pretty huge stipulation considering that the People’s Republic of China has been heavily invested in information technology R&D to revolutionize both its Armed Forces and its civilian infrastructure simultaneously for the past 20 years or so. The same is true for the Russian Federation (sans Sun Tzu, of course). I’d love to hear either of these two gentlemen discuss where they make the distinction between InfoSec for the enterprise versus InfoSec as an “expression of warfare by other means” (to paraphras...