首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > XML SOAP >

XML解析-XmlPullParser

2012-08-17 
XML解析------XmlPullParserXML解析------XmlPullParser工程结构图:[img][/img]运行效果图:[img][/img]一、

XML解析------XmlPullParser
XML解析------XmlPullParser

工程结构图:
[img]

[/img]

运行效果图:
[img]

[/img]

一、xml:



二、Student类:


三、MainActivity类:
package com.amaker.pullparser;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserException;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.util.Xml;public class MainActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                List<Student> list = readXML();        for(Student s:list){        Log.i("test", s.toString());        }            }        List<Student> readXML(){    InputStream in = this.getClass().getClassLoader().getResourceAsStream("stu.xml");    XmlPullParser parser = Xml.newPullParser();    List<Student> studentList = new ArrayList<Student>();    Student currentStudent = null;    try {parser.setInput(in, "utf-8");int eventType = parser.getEventType();while(eventType!=XmlPullParser.END_DOCUMENT){switch (eventType) {case XmlPullParser.START_TAG:String tagName = parser.getName();if(tagName!=null&&tagName.equals("student")){currentStudent = new Student();int id = Integer.parseInt(parser.getAttributeValue(null,"id"));currentStudent.setId(id);}if(tagName!=null&&tagName.equals("name")){String name;try {name = parser.nextText();currentStudent.setName(name);} catch (IOException e) {e.printStackTrace();}}if(tagName!=null&&tagName.equals("age")){String age;try {age = parser.nextText();currentStudent.setAge(Integer.parseInt(age));} catch (IOException e) {e.printStackTrace();}}break;case XmlPullParser.END_TAG:if(parser.getName().equals("student")){studentList.add(currentStudent);}break;default:break;}eventType = parser.next();}} catch (Exception e) {e.printStackTrace();}return studentList;    }}

热点排行