本文共 1818 字,大约阅读时间需要 6 分钟。
public class MainActivity extends Activity { private Button btn = null; private List > list = null; private XmlResourceParser xrp = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button)findViewById(R.id.btn); list = new ArrayList >(); xrp = this.getResources().getXml(R.xml.students); btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { Map map = null; String tag = ""; try { while(xrp.getEventType() != XmlResourceParser.END_DOCUMENT){ switch(xrp.getEventType()){ case XmlResourceParser.START_TAG: tag = xrp.getName(); if(tag.equalsIgnoreCase("student")){ map = new HashMap (); }else if(map != null){ if(tag.equalsIgnoreCase("id")){ map.put("id", xrp.nextText()); }else if(tag.equalsIgnoreCase("name")){ map.put("name", xrp.nextText()); } } break; case XmlResourceParser.END_TAG: if(xrp.getName().equalsIgnoreCase("student") && map!=null){ list.add(map); map = null; } break; } xrp.next(); } }catch (XmlPullParserException e) { e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } for(int i=0; i
xml/students.xml
1 张三 2 李四 3 王五
转载地址:http://xrmtx.baihongyu.com/