Android - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Android xml parser

Android xml parser

Extensible Mark-up Language (XML) is a popular format used for sharing data on the internet. Android xml parser allows you to parse XML data in Android applications. Of all parsers, Android recommends XMLPullParser as it is observed to be exceptionally efficient and easy to use. In this lesson, we are going to explain how to parse the XML file and extract information from it. XML Structure and Elements: Let us step XmlPullParser. First, create a xml file called employee.xml and copy the file to the assets folder of your project.(if you are using static data) [code lang="xml"] <? xml version="1.0"?> <employee> <details id="1"> <name>John B</name> <email>john@splessons.com </email> <phoneNumber>8978675645</phoneNumber> </details> <details id="2"> <name>Amit</name> <email>amit@splessons.com </email> <phonenumber>8979075645</phonenumber> </details> </employee> [/code] XMLPullParsing: First create XMLPullParser object by calling its newPullParser() method by using the XMLPullParserFactory object.
private XmlPullParserFactory xmlFactory= XmlPullParserFactory.newInstance();
private XmlPullParser parser = xmlFactory.newPullParser();
Next parse the XML, using XML methods:
int event = parser.getEventType();
while (event != XmlPullParser.END_DOCUMENT)
{
String tag=parser.getName();
switch (event){
case XmlPullParser.START_TAG:
if(tag.equals("details")){
id=parser.getAttributeValue(null, "id");
}

break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if(tag.equals("name ")){
name = text;
}
break;
}
event = parser.next();
}
Example: Create MainActivity.java under src/<package name> MainActivity.java: [java] public class MainActivity extends Activity { Context context; XMLPullParsing xmlObj; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //find views by Id Button access=(Button)findViewById(R.id.btnAccess); text=(TextView)findViewById(R.id.textViewId); context=this; //on click button access access.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { xmlObj=new XMLPullParsing(context); xmlObj.execute(); XMLPullParsing.h=new Handler() { public void handleMessage(android.os.Message msg) { if(msg.what==123) { System.out.println(xmlObj.emailL+"xml"+xmlObj.idL+""+xmlObj.nameL+""+xmlObj.numberL); text.setText(xmlObj.idL.get(0)+"\n"+xmlObj.nameL.get(0)+"\n"+xmlObj.emailL.get(0)+"\n"+xmlObj.numberL.get(0)+"\n\n\n"+xmlObj.idL.get(1)+"\n"+xmlObj.nameL.get(1)+"\n"+xmlObj.emailL.get(1)+"\n"+xmlObj.numberL.get(1)); } } }; } }); } } [/java] Create XMLPullParsing.java under src/<packagename> XMLPullParsing.java: [java] package com.spl.myproject; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.util.ArrayList; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; public class XMLPullParsing extends AsyncTask<String,String,String>{ private XmlPullParserFactory xmlFactory; int event; String text,id,name,email,number; static Handler h; Context context; ArrayList<String> nameL=new ArrayList<String>(); ArrayList<String> idL=new ArrayList<String>(); ArrayList<String> emailL=new ArrayList<String>(); ArrayList<String> numberL=new ArrayList<String>(); //constructor XMLPullParsing(Context context) { this.context=context; } @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub //create URL URL url; try { /*use this code if you are accessing data from server url = new URL("http://dev.splessons.com/simplexml.php"); //URL Encoding URI uri=new URI(url.getProtocol(),url.getUserInfo(),url.getHost(),url.getPort(),url.getPath(),url.getQuery(),url.getRef()); //convert URI to URL url=uri.toURL(); System.out.println(url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); InputStream stream = conn.getInputStream();*/ InputStream stream =context.getAssets().open("employee.txt"); xmlFactory = XmlPullParserFactory.newInstance(); XmlPullParser parser = xmlFactory.newPullParser(); parser.setInput(stream, null); event = parser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String tag=parser.getName(); switch (event){ case XmlPullParser.START_TAG: break; case XmlPullParser.TEXT: text = parser.getText(); break; case XmlPullParser.END_TAG: if(tag.equals("id")){ id=text; idL.add(id); } if(tag.equals("name")){ name = text; nameL.add(name); } else if(tag.equals("email")) { email=text; emailL.add(email); } else if(tag.equals("phonenumber")) { number=text; numberL.add(number); } break; } event = parser.next(); } h.sendEmptyMessage(123); } catch(Exception e) { e.printStackTrace(); } return null; } } [/java] Create activity_main.xml under res/layout folder. activity_main.xml: [code lang="xml"] <LinearLayout 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:orientation="vertical" android:background="#FFFFFF" tools:context=".MainActivity" > <Button android:id="@+id/btnAccess" android:layout_width="150dp" android:layout_height="wrap_content" android:gravity="center" android:background="#009ACD" android:layout_gravity="center" android:layout_marginTop="20sp" android:text="Access Data" /> <TextView android:id="@+id/textViewId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" /> </LinearLayout> [/code] AndroidManifest.xml: If you are accessing data from the server using HTTP connection, add Internet permission to your AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET"/>
[code lang="xml"] <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.spl.myproject" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.spl.myproject.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> [/code] Output: