import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import android.R.integer;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Xml;
import android.widget.Toast;
public class pulXmlPerson {
private Context context;
private Person person = null;
private List<Person> list = new ArrayList<Person>();
public pulXmlPerson(Context context) {
super();
// TODO Auto-generated constructor stub
this.context = context;
}
public List<Person> getPersons(String fileName) {
// 得到assets管理器
AssetManager assermanager = context.getAssets();
try {
// 得到inputstream
InputStream inputStream = assermanager.open(fileName);
//在android下使用pull解析xml文件
//1.获取pull解析器的实例
XmlPullParser xmlPullParser = Xml.newPullParser();
//2.设置解析器的一些参数
xmlPullParser.setInput(inputStream, "utf-8");
// 获取pull解析器对应的事件类型
while(type != xmlPullParser.END_DOCUMENT){
if(type == xmlPullParser.START_TAG){
if("person".equals(xmlPullParser.getName())){
person = new Person();
person.setAge(Integer.parseInt(xmlPullParser.getAttributeValue(0)));
}else if("name".equals(xmlPullParser.getName())){
person.setName(xmlPullParser.nextText());
}else if("age".equals(xmlPullParser.getName())){
person.setAge(Integer.parseInt(xmlPullParser.nextText()));
}
}
if(type == xmlPullParser.END_TAG){
if("person".equals(xmlPullParser.getName())){
list.add(person);
person = null;
}
}
type = xmlPullParser.next();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(context, "解析失败", 0).show();
}
return list;
}
}
要解析的xml编码格式要一致,文件本身编码
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="18">
<name>allen</name>
<age>36</age>
</person>
<person id="28">
<name>james</name>
<age>25</age>
</person>
</persons>
package com.example.pullxml;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.tv);
StringBuffer stringBuffer = new StringBuffer();
List<Person> list = new pulXmlPerson(MainActivity.this).getPersons("person.xml");
for (Person person : list) {
String name = person.getName();
String age = "年龄="+person.getAge();
String id = "id="+person.getId();
stringBuffer.append(name+" "+age+" "+id+" ");
}
String string = stringBuffer.toString();
textView.setText(string);
}
}
for循环输出list集合
注意:xml文件头前面(就是开头最前面)不能有回车和空格,否则报错