Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Android DOM Parser Example



In this example we will see how to parse an XML file using DOM Parser in Android. What we do here is load the .xml file in the assets folder and parse the content inside and show them in a text view. When compared to SAX Parser(refer : Android SAX Parser Example ) , DOM is slow and will consume a lot of memory when it loads an XML document which contains a lot of data.


Okay let us start:

1.Create an xml file (file.xml) like below

file.xml
<?xml version="1.0"?>
<food>
<item>
<name>French Toast</name>
<price>$4.50</price>
</item>
<item>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
</item>
<item>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
</item>
</food>
2. Create a new project File ->New -> Project ->Android ->Android Application Project. While creating a new project give activity name as DOMParserActivity(DOMParserActivity.java). Copy and paste the xml file inside the assets folder of the android project.

DOMParserActivity.java:
package com.aj.dom;

import java.io.InputStream;

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

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

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class DOMParserActivity extends Activity {
 TextView tv1;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  tv1 = (TextView) findViewById(R.id.textView1);
  try {
   InputStream is = this.getAssets().open("file.xml");

   DocumentBuilderFactory dbFactory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
   Document doc = dBuilder.parse(is);
   doc.getDocumentElement().normalize();
   NodeList nList = doc.getElementsByTagName("item");
   for (int temp = 0; temp < nList.getLength(); temp++) {
    Node nNode = nList.item(temp);
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
     Element eElement = (Element) nNode;
     tv1.setText(tv1.getText() + "\n\nName : "
       + getValue("name", eElement) + "\n");
     tv1.setText(tv1.getText() + "Price : "
       + getValue("price", eElement) + "\n");
     tv1.setText(tv1.getText() + "-----------------------");

    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 private static String getValue(String sTag, Element eElement) {
  NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
    .getChildNodes();
  Node nValue = (Node) nlList.item(0);
  return nValue.getNodeValue();
 }

}

3. Now in the main.xml, add the id attribute for the TextView to be used in the DOMParserActivity


main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="DOM Parser Example"
        tools:context=".DOMParserActivity" />

</RelativeLayout>
4.Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows:

Android SAX Parser Example


In this example we will see how to parse an XML file using SAX Parser in Android. What we do here is load the .xml file in the assets folder and parse the content inside and show them in a text view.

To do parsing we use the following callback methods :
  • startDocument() and endDocument() is called at the start and end of the document.
  • startElement() and endElement() is called at the start and end of the element.
  • characters() is called with the text contents between the element.
So let us start:

1.Create an xml file (file.xml) like below

file.xml

<?xml version="1.0"?>
<contacts>
<contact>
<firstname>Sachin</firstname>
<lastname>Tendulkar</lastname>
<email>sachin@xyz.com</email>
<phone>9999999999</phone>
</contact>
<contact>
<firstname>Brain</firstname>
<lastname>Lara</lastname>
<email>lara@xyz.com</email>
<phone>9999999999</phone>
</contact>
<contact>
<firstname>Steve</firstname>
<lastname>Waugh</lastname>
<email>steve@xyz.com</email>
<phone>9999999999</phone>
</contact>
</contacts>
2. Create a new project File ->New -> Project ->Android ->Android Application Project. While creating a new project give activity name as SAXParserActivity(SAXParserActivity.java). Copy and paste the xml file inside the assets folder of the android project. In the activity we parse the xml file using the org.xml.sax.helpers.DefaultHandler.

SAXParserActivity.java:
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SAXParserActivity extends Activity {
 TextView tv;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  tv = (TextView) findViewById(R.id.textView1);
  try {
   SAXParserFactory factory = SAXParserFactory.newInstance();
   SAXParser saxParser = factory.newSAXParser();
   DefaultHandler handler = new DefaultHandler() {
    boolean bfname = false;
    boolean blname = false;
    boolean bemail = false;
    boolean bphone = false;

    public void startElement(String uri, String localName,
      String qName, Attributes attributes)
      throws SAXException {
     if (qName.equalsIgnoreCase("FIRSTNAME")) {
      bfname = true;
     }
     if (qName.equalsIgnoreCase("LASTNAME")) {
      blname = true;
     }
     if (qName.equalsIgnoreCase("EMAIL")) {
      bemail = true;
     }
     if (qName.equalsIgnoreCase("PHONE")) {
      bphone = true;
     }
    }

    public void endElement(String uri, String localName,
      String qName) throws SAXException {
    }

    public void characters(char ch[], int start, int length)
      throws SAXException {
     if (bfname) {
      tv.setText(tv.getText() + "\n\n First Name : "
        + new String(ch, start, length));
      bfname = false;
     }
     if (blname) {
      tv.setText(tv.getText() + "\n Last Name : "
        + new String(ch, start, length));
      blname = false;
     }
     if (bemail) {
      tv.setText(tv.getText() + "\n Email : "
        + new String(ch, start, length));
      bemail = false;
     }
     if (bphone) {
      tv.setText(tv.getText() + "\n Phone : "
        + new String(ch, start, length));
      bphone = false;
     }
    }
   };
   InputStream is = this.getAssets().open("file.xml");
   saxParser.parse(is, handler);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
3. Now in the main.xml, add the id attribute for the TextView to be used in the SAXParserActivity


main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="SAX Parser Example" />

</LinearLayout>
4.Run the project by rightclicking project Run as → android project. This project is tested with amdroid API level 8

Output:

The output of this example would be similar to the one as follows: