Selasa, 24 Desember 2013

Tutorial : How to parsing XML on Android (standard)

For example data :

Package Name : com.example.xmllesson

Note : you will not see this result on your UI, you can see this result if you debug this code on MainActivity.java (there are have sign to you debug)











data xml to parsing : (in MainActivity, you will find method Dummy, so you dont need to copy this)

<friends>
    <friend id="0001">
        <name>
            <first>first_1</first>
            <middle>middle_1</middle>
            <last>last_1</last>
        </name>
        <photo url="http://www.example.com/friend1.jpg"/>
        <address>Friend Address 1</address>
    </friend>
   
    <friend id="0002">
        <name>
            <first>first_2</first>
            <middle>middle_2</middle>
            <last>last_2</last>
        </name>
        <photo url="http://www.example.com/friend2.jpg"/>
        <address>Friend Address 2</address>
    </friend>
</friends>


XMLDOMParser.java

package com.example.xmllesson;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLDOMParser {

    public Document getDocument(InputStream inputStream) {
        Document document = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inputSource = new InputSource(inputStream);
            document = db.parse(inputSource);
        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }
        return document;
    }

    public String getValue(Element item, String name) {
        NodeList nodes = item.getElementsByTagName(name);
        return this.getTextNodeValue(nodes.item(0));
    }

    public String getTextNodeValue(Node node) {
        Node child;
        if (node != null) {
            if (node.hasChildNodes()) {
                child = node.getFirstChild();
                while(child != null) {
                    if (child.getNodeType() == Node.TEXT_NODE) {
                        return child.getNodeValue();
                    }
                    child = child.getNextSibling();
                }
            }
        }
        return "";
    }
}


FriendModel.java

package com.example.xmllesson;

public class FriendModel {
   
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getFullname() {
        String fullname = "";
        if(!getFirst().equals(null))
            fullname = getFirst();
        if(!getMiddle().equals(null))
            fullname = fullname + " " + getMiddle();
        if(!getLast().equals(null))
            fullname = fullname + " " + getLast();
        return fullname;
    }

    public String getFirst() {
        return first;
    }
    public void setFirst(String first) {
        this.first = first;
    }
    public String getMiddle() {
        return middle;
    }
    public void setMiddle(String middle) {
        this.middle = middle;
    }
    public String getLast() {
        return last;
    }
    public void setLast(String last) {
        this.last = last;
    }
    public String getPhoto() {
        return photo;
    }
    public void setPhoto(String photo) {
        this.photo = photo;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    private String id;
    private String first;
    private String middle;
    private String last;
    private String photo;
    private String address;


ParserXML.java

package com.example.xmllesson;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class ParserXML {
    private static final String NODE_FRIEND = "friend";
    private static final String ATTR_ID = "id";
    private static final String NODE_NAME = "name";
    private static final String NODE_FIRST = "first";
    private static final String NODE_MIDDLE = "middle";
    private static final String NODE_LAST = "last";
    private static final String NODE_PHOTO = "photo";
    private static final String ATTR_URL = "url";
    private static final String NODE_ADDRESS = "address";
    private static XMLDOMParser parser;
   
    public static ArrayList<FriendModel> Desrialize(String xmlString)
    {
        ArrayList<FriendModel> listFriend = new ArrayList<FriendModel>();
        parser = new XMLDOMParser();
        InputStream stream = new ByteArrayInputStream(xmlString.getBytes());
        Document doc = parser.getDocument(stream);
        NodeList nodeList = doc.getElementsByTagName(NODE_FRIEND);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element e = (Element) nodeList.item(i);
            FriendModel friend = new FriendModel();
           
            //<friend id="0001"> we will get : id = 0001
            friend.setId(e.getAttribute(ATTR_ID));
           
            //<first>first_1</first> we will get : first_1
            friend.setFirst(getTextNodeValueInNode(e, NODE_NAME, NODE_FIRST));
           
            //<middle>middle_1</middle> we will get : middle_1
            friend.setMiddle(getTextNodeValueInNode(e, NODE_NAME, NODE_MIDDLE));
           
            //<last>last_1</last> we will get : last_1
            friend.setLast(getTextNodeValueInNode(e, NODE_NAME, NODE_LAST));
           
            //<photo url="http://www.example.com/friend1.jpg"/> we will get : http://www.example.com/friend1.jpg
            friend.setPhoto(getAttributeInNodeItem(e, NODE_PHOTO, ATTR_URL));
           
            //<address>Friend Address 1</address> we will get : Friend Address 1
            friend.setAddress(parser.getValue(e, NODE_ADDRESS));
           
           
            listFriend.add(friend);
        }
        return listFriend;
    }

    private static String getTextNodeValueInNode(Element item, String nodeName, String subNodeName)
    {
        NodeList childs = item.getElementsByTagName(nodeName);
        Element element = (Element)childs.item(0);
        return parser.getValue(element, subNodeName);
    }
   
    private static String getAttributeInNodeItem(Element item, String name, String attrName)
    {
        NodeList childs = item.getElementsByTagName(name);
        return ((Element) childs.item(0))
                .getAttribute(attrName);
    }
}


MainActivity.java

package com.example.xmllesson;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //debug here
        ArrayList<FriendModel> result = ParserXML.Desrialize(Dummy());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private String Dummy() {
        return "<friends>" + "    <friend id=\"0001\">" + "        <name>"
                + "            <first>first_1</first>" + "            <middle>middle_1</middle>"
                + "            <last>last_1</last>" + "        </name>"
                + "        <photo url=\"http://www.example.com/friend1.jpg\"/>"
                + "        <address>Friend Address 1</address>" + "    </friend>" + "    "
                + "    <friend id=\"0002\">" + "        <name>"
                + "            <first>first_2</first>" + "            <middle>middle_2</middle>"
                + "            <last>last_2</last>" + "        </name>"
                + "        <photo url=\"http://www.example.com/friend2.jpg\"/>"
                + "        <address>Friend Address 2</address>" + "    </friend>"
                + "</friends>";
    }
}




So, keep learning anything and keep spirit ^_^

Tidak ada komentar:

Posting Komentar