Android에서 제공하는 XML 파서 XmlPullParser 예제
Java SE6 기반에서도 이와 유사한 특성을 가진 API가 제공됩니다. 여기를 참조하세요
res/xml/people
<?xml version="1.0" encoding="utf-8" ?> <people> <person name="강호동"/> <person name="이수근"/> <person name="은지원"/> <person name="엄태웅"/> <person name="김종민"/> </people>
res/layout/xmldemo.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout>
XmlDemo.java
package android.test.app;
import java.util.*;
import org.xmlpull.v1.XmlPullParser;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
public class XmlDemo extends ListActivity {
TextView tv;
ArrayList<String> items = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xmldemo);
tv = (TextView) findViewById(R.id.textView1);
try{
XmlPullParser xpp = getResources().getXml(R.xml.people);
while(xpp.getEventType()!=XmlPullParser.END_DOCUMENT){
if(xpp.getEventType()==XmlPullParser.START_TAG){
if(xpp.getName().equals("person")){
items.add(xpp.getAttributeValue(0));
}
}
xpp.next();
} // end of while()
}catch(Throwable t){
Toast.makeText(this, "오류", Toast.LENGTH_SHORT).show();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
setListAdapter(adapter);
}
public void onListItemClick(ListView parent, View v, int position, long id){
tv.setText(items.get(position).toString());
}
}