核心代码如下:
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
XmlPullParser parser = resources.getXml(R.xml.people);
String msg = "";
try {
while(parser.next()!=XmlPullParser.END_DOCUMENT){
String people = parser.getName();
String name = null;
String age = null;
String height =null;
if((people!=null)&&people.equals("person")){
int count = parser.getAttributeCount();
for(int i=0;i<count;i++){
String attrName = parser.getAttributeName(i);
String attrValue = parser.getAttributeValue(i);
if(attrName!=null&&"name".equals(attrName)){
name = attrValue;
}
if(attrName!=null&&"age".equals(attrName)){
age = attrValue;
}
if(attrName!=null&&"height".equals(attrName)){
height = attrValue;
}
}
if((name!=null)&&(age!=null)&&(height!=null)){
msg+="姓名:"+name+",年龄:"+age+",身高:"+height+"\n";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
display.setText(msg);
}
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});