Thursday 22 March 2012

Android Dom Parser Example



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.SAXParser;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class DemoDomParser extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       parserDom();
    }
   
    private  void parserDom(){
    URL rssurl;
try {
rssurl = new URL("http://feeds.bbci.co.uk/news/technology/rss.xml");

    Document dom = XMLfunctions.XMLfromString(convertStreamToString(rssurl.openStream()));
         Element root = dom.getDocumentElement();
         NodeList items = root.getElementsByTagName("item");
   
     
         for (int i=0;i<items.getLength();i++){
             Element item = (Element)items.item(i);
         
          Log.i("TEST","Title: "+XMLfunctions.getValue(item, "title"));
          Log.i("TEST","Description: "+XMLfunctions.getValue(item, "description"));
         
         }
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    }
    public String convertStreamToString(InputStream is) throws IOException {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                is.close();
            }
            return sb.toString();
        } else {      
            return "";
        }
    }

}


XMLFunction.java






import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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;


public class XMLfunctions {

public final static Document XMLfromString(String xml){

Document doc = null;

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
       
DocumentBuilder db = dbf.newDocumentBuilder();

InputSource is = new InputSource();
       is.setCharacterStream(new StringReader(xml));
       doc = db.parse(is);
     
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
     
        return doc;
       
}

/** Returns element value
 * @param elem element (it is XML tag)
 * @return Element value otherwise empty String
 */
public final static String getElementValue( Node elem ) {
    Node kid;
    if( elem != null){
        if (elem.hasChildNodes()){
            for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                if( kid.getNodeType() == Node.TEXT_NODE  ){
                    return kid.getNodeValue();
                }
            }
        }
    }
    return "";
}


public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;

try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}

return res;
}

public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
}


4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. very clear explanation , I like this tutorial, very find day i got this tutorial, thank you.....

    ReplyDelete
  3. here 4 types of parse() are there , what is difference between those 4 parse() methods? ex: d.parse("jana.xml");

    ReplyDelete