Android Pull 解析 XML
openkk
12年前
下面是效果图,代码中有详细解释,
res/raw/person.xml
<?xml version="1.0" encoding="UTF-8"?> <persons> <person id="001"> <name>张三</name> <age>22</age> </person> <person id="002"> <name>李四</name> <age>23</age> </person> <person id="003"> <name>王五</name> <age>24</age> </person> </persons>PullParse.java
public class PullParse { public static List<Person> parse(InputStream inputStream) throws Exception{ List<Person> persons=null; Person person=null; XmlPullParser parser=Xml.newPullParser(); parser.setInput(inputStream, "UTF-8"); int event=parser.getEventType(); while(event!=XmlPullParser.END_DOCUMENT){ switch(event){ //判断当前事件是否是文档开始事件 case XmlPullParser.START_DOCUMENT: persons=new ArrayList<Person>(); break; //判断当前事件是否是标签元素开始事件 case XmlPullParser.START_TAG: //判断开始标签元素是否是book if("person".equals(parser.getName())){ person=new Person(); person.setId(new Integer(parser.getAttributeValue(0))); } if(person!=null){ if("name".equals(parser.getName())){ person.setName(parser.nextText()); }else if("age".equals(parser.getName())){ person.setAge(new Integer(parser.nextText())); } } break; //判断当前事件是否是标签元素结束事件 case XmlPullParser.END_TAG: //判断结束标签元素是否是person if("person".equals(parser.getName())){ persons.add(person);//将person添加到persons集合 person = null; } break; } //进入下一个元素并触发相应事件 event = parser.next(); } return persons; } }
在主程序中调用
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn=(Button) findViewById(R.id.button); listView=(ListView) findViewById(R.id.listView); btn.setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { try { InputStream i =getResources().openRawResource(R.raw.person); List<Person>persons = PullParse.parse(i); for (Iterator iterator = persons.iterator(); iterator.hasNext();) { Person person = (Person) iterator.next(); list.add(String.valueOf("ID:"+person.getId()) + " 姓名: " + person.getName() + " 年龄: " + person.getAge()); } } catch (Exception e) {} ArrayAdapter<String> adapter = new ArrayAdapter<String>( getApplicationContext(), android.R.layout.simple_list_item_1, list); listView.setAdapter(adapter); } }); }