Read XML file in Android Example


          Reading XML is one of the basic functionality in any programming language. Here, lets see how to parse XML file in Android with an simple example. Android provides three types of XML parsers which are SAX, DOM and XMLPullParser.
Among all of them android recommends XMLPullParser. So we are going to use XMLPullParser for parsing XML, because it is an efficient and maintainable way to parse XML on Android. Now lets see how to code this.
Below is the XML we are about to parse :

<?xml version="1.0"?>
 <food>
     <name>French Toast</name>
     <price>$4.50</price>
     <description>Thick slices made from our homemade sourdough bread</description>
     <calories>600</calories>
 </food>

Step 1 : Read XML file to InputStream
         This InputStream will be the input to XML parser
inputstream = this.getResources().openRawResource(R.drawable.xmldata);

where xmldata is the XML file that is to be parsed, which is placed under drawable folder as shown below.


Step 2 : Instantiate XMLPullParser
         Here will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its syntax is given below :
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();

Step 3: Set Input to XMLPullParser
         Next steps is to define input to XMLPullParser, input to this XMLPullParser is going to be the inputstream that we defined earlier.
myparser.setInput(inputstream, null);

The actual file is placed under drawable folder as shown above.

Step 4: Parse the XML
         This is the important step where in we are going to read the XML.

event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;

case XmlPullParser.END_TAG:
if (name.equals("name")) {
a = text;
} else if (name.equals("price")) {
b = text;
} else if (name.equals("description")) {
c = text;
} else if (name.equals("calories")) {
d = text;
} else {
}
break;
}
event = myParser.next();
}
parsingComplete = false;

Method getEventType returns the type of event that happens. (Document start , tag start) The method getName returns the name of the tag .

<name>              --> Start Tag
French Toast      -->Text
</name>             -->End Tag

Thats it, now print your variables and you will the output shown below


activity_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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

MainActivity.java

import java.io.InputStream;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Log.d("Tag Name", "IS");
InputStream inputstream;
try {
inputstream = this.getResources().openRawResource(
R.drawable.xmldata);
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(inputstream, null);
Log.d("Tag Name", "Before cal");
parseXMLAndStoreIt(myparser);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text = null;
String a = null, b = null, c = null, d = null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;

case XmlPullParser.END_TAG:
if (name.equals("name")) {
a = text;
} else if (name.equals("price")) {
b = text;
} else if (name.equals("description")) {
c = text;
} else if (name.equals("calories")) {
d = text;
} else {
}
break;
}
event = myParser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
TextView txtView = (TextView) findViewById(R.id.textView1);
txtView.setText("Name : " + a + "\nPrice : " + b + "\nDescription : "
+ c + "\nCalories : " + d);
}
@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;
}

}




Reactions:

1 comment :

  1. Thanks... Its amazing.. Got to learn perfectly

    ReplyDelete