2016. 11. 29. 10:31ㆍAndroid
XML 파서: XmlPullParser
1. xml 데이터
res에 raw 폴더를 만들어 student.xml 파일을 만든다.
<person>
<student>
<name>홍길동</name>
<age>30</age>
<address>서울</address>
</student>
<student>
<name>이순신</name>
<age>40</age>
<address>전라도</address>
</student>
<student>
<name>강감찬</name>
<age>50</age>
<address>경상도</address>
</student>
</person>
2. 자바빈 생성
java 폴더에서 위의 xml 데이터를 기본으로 한 student.java라는 자바빈 클래스를 정의한다.
package com.progdv.xmlpullparser;
public class Student {
String name;
String age;
String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
3. 레이아웃
<?xml version="1.0" encoding="utf-8"?>
<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="com.progdv.xmlpullparser.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:background="#314eac"
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
4. xml 파일을 가져와서 뿌려주는 메인 액티비티
xmlPullParser 방식으로 가져온다.
package com.progdv.xmlpullparser;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
ArrayList<Student> list = xmlParser();
String[] data = new String[list.size()];
for(int i=0;i<list.size();i++) {
data[i] = list.get(i).getName()+" "+
list.get(i).getAge()+" "+list.get(i).getAddress();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1,
data);
listView.setAdapter(adapter);
}
private ArrayList<Student> xmlParser() {
ArrayList<Student> arrayList = new ArrayList<Student>();
InputStream is = getResources().openRawResource(R.raw.student);
// xmlPullParser
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(new InputStreamReader(is, "UTF-8"));
int eventType = parser.getEventType();
Student student = null;
while(eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
String startTag = parser.getName();
if(startTag.equals("student")) {
student = new Student();
}
if(startTag.equals("name")) {
student.setName(parser.nextText());
}
if(startTag.equals("age")) {
student.setAge(parser.nextText());
}
if(startTag.equals("address")) {
student.setAddress(parser.nextText());
}
break;
case XmlPullParser.END_TAG:
String endTag = parser.getName();
if(endTag.equals("student")) {
arrayList.add(student);
}
break;
}
eventType = parser.next();
}
}catch(XmlPullParserException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return arrayList;
}
}
[출처] http://mainichibenkyo.tistory.com/317
=========================================================================================
<?xml version="1.0" encoding="utf-8"?>
<board> <content name="유재석" /> <content name="박명수" /> <content name="정준하" /> <content name="정형돈" /> <content name="노홍철" /> <content name="하하" /> <content name="길" /> </board>
package com.example.android_test1;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
ArrayList<String> items = new ArrayList<String>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
XmlPullParser parser = getResources().getXml(R.xml.board);
while(parser.getEventType() != XmlPullParser.END_DOCUMENT) {
if(parser.getEventType() == XmlPullParser.START_TAG) {
if(parser.getName().equals("content")) {
items.add(parser.getAttributeValue(0));
}
}
parser.next();
}
}catch(Throwable t) {
}
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) {
Toast.makeText(this, items.get(position).toString(), Toast.LENGTH_LONG ).show();
}
}
'Android' 카테고리의 다른 글
웹뷰(1) (0) | 2018.06.08 |
---|---|
안드로이드 캐시(Cache) 사용하기 (0) | 2017.01.12 |
Android Google Chart 사용하기 (0) | 2016.11.25 |
안드로이드에서 백버튼 두 번 눌러 종료하기 (0) | 2016.10.21 |
Realm 모바일 데이터 베이스(Android) (0) | 2016.04.26 |