Thursday, October 27, 2011

Get XML parse event; using XmlResourceParser.getEventType()

The XML parsing interface returned for an XML resource. This is a standard XmlPullParser interface, as well as an extended AttributeSet interface and an additional close() method on this interface for the client to indicate when it is done reading the resource.

Normally, xml file will be placed under /res/xml/ folder; as a example /res/layout/main.xml is used here.

Get XML parse event; using XmlResourceParser.getEventType()

package com.exercise.XmlResourceParser;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidXmlParserActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView result = (TextView)findViewById(R.id.result);

String XmlParseResult = getXmlEvent();
result.setText(XmlParseResult);
}

private String getXmlEvent(){
String xmlResult = "";

//Normally, the XML files should be placed under /res/xml/ folder
//XmlResourceParser xmlResourceParser = getResources().getXml(R.xml.xxx);
XmlResourceParser xmlResourceParser = getResources().getXml(R.layout.main);

try {
int eventType;
do{
xmlResourceParser.next();
eventType = xmlResourceParser.getEventType();

switch(eventType){
case XmlPullParser.START_DOCUMENT:
xmlResult += "START_DOCUMENT\n";
break;
case XmlPullParser.END_DOCUMENT:
xmlResult += "END_DOCUMENT\n";
break;
case XmlPullParser.START_TAG:
xmlResult += "START_TAG: " + xmlResourceParser.getName() + "\n";
break;
case XmlPullParser.END_TAG:
xmlResult += "END_TAG: " + xmlResourceParser.getName() + "\n";
break;
case XmlPullParser.TEXT:
xmlResult += "TEXT: " + xmlResourceParser.getText() + "\n";
break;
}

}while (eventType != XmlPullParser.END_DOCUMENT);

} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return xmlResult;
}
}


/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>


Download the files.



No comments:

Post a Comment