Minggu, 02 Desember 2012

Introduction JDOM2

Hi..hi...sorry if the tittle english but the content indonesian :p.
Hari ini mau posting tentang jdom2 library. Bagi yg belum kenal apa itu jdom, saya akan sedikit bercerita apa itu jdom. Jdom itu erat kaitannya dengan XML di java. Kalau kalian mengenal java, maka harus kenal pula itu jdom :). Karena beberapa framework dan server di java menggunakan xml, contohnya hibernate, jetty, dll.
Oke langsung aja ke code ya, hari ini mau tulis gimana create xml menggunakan jdom2.

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;


/**
 *
 * @author user
 */
public class WriteXML {

    public static void main(String[] args) {
        Element root = new Element("Articles");     // root element
        Document doc = new Document(root);

        Element article = new Element("Article");    // child element
        root.addContent(article);

        Attribute att1 = new Attribute("classe", "Al");
        article.setAttribute(att1);
        Attribute att2 = new Attribute("logger", "Q2");
        article.setAttribute(att2);
        
        Element titre = new Element("Titre");
        titre.setText("Hello world!");
        article.addContent(titre);
        
        
        save("file.xml", doc);
    }

    static void save(String file, Document doc) {
        try {
            XMLOutputter xmlop = new XMLOutputter(Format.getPrettyFormat());
            xmlop.output(doc, new FileOutputStream(file));
        } catch (IOException e) {
        }        
    }
}

Nanti outputnya ada di file xml
<?xml version="1.0" encoding="UTF-8"?>
<Articles>
  <Article classe="Al" logger="Q2">
    <Titre>Hello world!</Titre>
  </Article>
</Articles>

Mudah bukan, dan untuk membacanya juga cukup mudah. Berikut kodenya :

import java.io.File;
import java.util.Iterator;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import java.util.List;

/**
 *
 * @author user
 */
public class ReadXML {

    public static void main(String[] args) {
        Document doc = null;
        SAXBuilder sxb = new SAXBuilder();
        try {
            doc = sxb.build(new File("file.xml"));
        } catch (Exception e) {
        }

        Element root = doc.getRootElement();
        List<Element> lstArticle = root.getChildren("Article");
        Iterator<Element> i = lstArticle.iterator();

        while (i.hasNext()) {
            Element current = (Element) i.next();
            System.out.println(current.getChild("Titre").getText());
        }
    }
}

Outputnya :
Hello world!

Mudah bukan, sekian dari saya
Wassalam  :)

0 komentar:

Posting Komentar