一丶代码见本文
二丶课程讲解
public class XMLparse extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_xmlparse); } /*** * 使用 pull 解析 xml文件 * * @param view */ public void xmlPullClic(View view) { ArrayList<Person> plist = parse();//解析xml for (int i = 0; i < plist.size(); i++) { System.out.print(plist.get(i)); } } private ArrayList<Person> parse() { //封装xmL节点信息 ArrayList<Person> list = new ArrayList<Person>(); //封装对象 Person p = null; //创建xml 解析器 XmlPullParser pull = Xml.newPullParser(); // StringReader st = new StringReader(xml); InputStream in = getResources().openRawResource(R.raw.info); try { pull.setInput(in,"utf-8");//xml文件流 int eventType = pull.getEventType();//获取当前的事件类型 while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: //开时位置时 :读取内容 String tag = pull.getName();//标记名称 if ("person".equals(tag)) { p = new Person(); p.setId(Integer.parseInt(pull.getAttributeValue(null,"id"))); //获取标记属性 id } else if ("name".equals(tag)) { p.setName(pull.nextText());//因为文本在标记里面,所以要用 nextText() } else if ("age".equals(tag)) { p.setAge(Integer.parseInt(pull.nextText())); } else if ("sex".equals(tag)) { p.setSex(pull.nextText()); } else if ("tel".equals(tag)) { p.setTel(pull.nextText()); } else if ("address".equals(tag)) { p.setAddress(pull.nextText()); } break; case XmlPullParser.END_TAG: if ("person".equals(pull.getName())) { list.add(p); } break; } eventType = pull.next();//下一个事件类型 } } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return list; //xml解析后返回的结果 } }这里只是一个理解,做了解,后期加强 原文链接:https://www.f2er.com/xml/295709.html