Introduction
In this article you will learn about XML parsing with the pull parser.
XML Parsing
XML parsing is a process of converting data from a server in a machine-readable form.
XML pull parser
The XML pull parser is an interface that defines the parsing functionality. It provides two key methods next() that provides acess to high level parsing event. The current event state of the parser can be determined by the geteventType() method. Initially the parser lies in the START_DOCUMENT state.
The following are the events seen by next():
START_TAG an XML start tag was read.
Text
Text content was read. The text content was retrieved using the getText() method.
END_TAG
A tag was read.
END_DOCUMENT
No more events are available.
Step 1
Create an XML file and write this:
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
Step 2
Create a Java file MainActivity.java and write this:
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.NodeList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
public class MainActivity extends ListActivity {
private static String BASE_URL = "http://maps.googleapis.com/maps/api/geocode/xml?address=NewDelhi&sensor=false";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
(new ProgressTask(MainActivity.this)).execute();
}
@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;
}
public class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private Context context;
public ProgressTask(ListActivity activity) {
Log.i("1", "Called");
context = activity;
dialog = new ProgressDialog(context);
}
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
@Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected Boolean doInBackground(final String... args) {
String xml = getXmlFromUrl(BASE_URL);
// useParserType1(xml);
useParserType2(xml);
return null;
}
}
//DOM Parser
public void useParserType1(String xml){
XmlParsingType1 parser = new XmlParsingType1();
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList GeocodeResponse = doc.getElementsByTagName("location");
for (int i = 0; i < GeocodeResponse.getLength(); i++) {
Element e = (Element) GeocodeResponse.item(i);
Log.i("xml", parser.getValue(e,"lat"));
Log.i("xml", parser.getValue(e,"lng"));
}
}
//XmlPull Parser
public void useParserType2(String xml){
try{
Boolean flagLocation = false;
Boolean flagLatitude = false;
Boolean flagLongitude = false;
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(xml));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
} else if(eventType == XmlPullParser.END_DOCUMENT) {
} else if(eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("location")) flagLocation=true;
if (flagLocation && xpp.getName().equalsIgnoreCase("lat")) flagLatitude=true;
if (flagLocation && xpp.getName().equalsIgnoreCase("lng")) flagLongitude=true;
} else if(eventType == XmlPullParser.END_TAG) {
if (xpp.getName().equalsIgnoreCase("location")) flagLocation=false;
if (flagLocation && xpp.getName().equalsIgnoreCase("lat")) flagLatitude=false;
if (flagLocation && xpp.getName().equalsIgnoreCase("lng")) flagLongitude=false;
} else if(eventType == XmlPullParser.TEXT) {
if (flagLatitude)
Log.i("Latitude: ", xpp.getText());
if (flagLongitude)
Log.i("Longitude: ", xpp.getText());
}
eventType = xpp.next();
}
}catch (XmlPullParserException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
}
Step 3
Create another Java class file XMLParser.java and write this:
import android.util.Log;
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 java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* Created by naveen on 19/06/13.
*/
public class XmlParsingType1 {
public Document getDomElement(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) {
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 DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
}
output
See Logacat