package com.example.weekthree;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
List list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 开始解析
pullll();
Log.i(“TAG”, list.toString());
Toast.makeText(MainActivity.this, list.toString(), 0).show();
}
public void pullll() {
try {
Person musics = null;
//得到游标工厂
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
// 获取文件
parser.setInput(getAssets().open("Pserson.xml"), "UTF-8");
// 定义一个类型 判断是否 是哪个类型
int type_pull = parser.getEventType();
// 判断是不是结束接收文件
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
switch (type_pull) {
case XmlPullParser.START_DOCUMENT:// 开始接收文件
list = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG:// 开始解析文件
if ("persona".equals(parser.getName())) {
musics = new Person();
musics.setId(Integer.valueOf(parser.getAttributeValue(null, "id")));
} else if (musics != null) {
if ("name".equals(parser.getName())) {
musics.setName(parser.nextText());
} else if ("age".equals(parser.getName())) {
musics.setAge(parser.nextText());
}else if("hobby".equals(parser.getName())){
musics.setHobby(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:// 结束解析文件
if ("persona".equals(parser.getName())) {
list.add(musics);
}
break;
default:
break;
}
type_pull = parser.next();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}