使用PULL方式解析XML资源文件下面的xml文件
public class MainActivity extends Activity { private Button btn = null; private List<Map<String,String>> 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<Map<String,String>>(); xrp = this.getResources().getXml(R.xml.students); btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { Map<String,String> 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<String,String>(); }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<list.size(); i++){ Log.d("+id+", list.get(i).get("id")); } } }); } }
xml/students.xml
<?xml version="1.0" encoding="UTF-8"?> <students> <student> <id>1</id> <name>张三</name> </student> <student> <id>2</id> <name>李四</name> </student> <student> <id>3</id> <name>王五</name> </student> </students>