package com.example.day14_xmlpull; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.os.Bundle; import android.app.Activity; import android.util.Xml; import android.view.Menu; import android.view.View; /** * Parse Xml * * @author gaoyn * */ public class MainActivity extends Activity { List<Person> persons = new ArrayList<Person>(); private String tagname; Person p; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView(R.layout.activity_main); } // method to parse xml file public void pullxml(View v) { // 1 get the pull parser XmlPullParser xmlParser = Xml.newPullParser (); try { // 2 Load the file that needs to be parsed xmlParser.setInput(getAssets().open("data.xml"), "utf-8"); // 3 start reading the document int type = xmlParser.getEventType (); // If the document does not read the end tag, loop to read the document content while (type != XmlPullParser.END_DOCUMENT) { // read the tag tag switch (type) { case XmlPullParser.START_DOCUMENT: System.out.println("Start reading document +++++++++++++++++"); break; case XmlPullParser.START_TAG: // If the start tag is read, read the tag name <person> tagname = xmlParser.getName(); System.out.println(tagname+"++++++++++++++++tagname"); if (tagname.equals("person")) { p = new Person(); // Get the attribute value in the tag person String sid = xmlParser.getAttributeValue(0).trim(); p.setId(Integer.parseInt(sid)); } break; case XmlPullParser.TEXT: if (tagname.equals("name")) { p.setName(xmlParser.getText()); } else if (tagname.equals("age")) { // System.out.println(xmlParser.getText()); String sage = xmlParser.getText().trim(); p.setAge(Integer.parseInt(sage)); } break; case XmlPullParser.END_TAG: //At the end, assign a value to the label name tagname=xmlParser.getName(); //if the closing tag is </person> if (tagname.equals("person")) { persons.add(p); } tagname=""; break; default: break; } /** * Business logic processing */ type = xmlParser.next(); } System.out.println("Read the document ++++++++++++++++++" + persons); } catch (XmlPullParserException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); } } }