【Android基础知识】网络获取Xml文件并解析

从服务器获取xml内容并解析

girls.xml



	
		tian
		12
		tianting
	
	
		di
		12
		庞各庄
	
xml解析类 Xmlparse.java

public class XmlParse extends Thread {
	String url;
	public XmlParse(String url){
		this.url = url;
	}
	@Override
	public void run() {
		
		try {
			//获取xml并使用pull方式解析
			URL httpUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
			connection.setReadTimeout(3000);
			connection.setRequestMethod("GET");
			InputStream in = connection.getInputStream();
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = factory.newPullParser();
                        //读取xml内容,以UTF-8的格式
			parser.setInput(in,"UTF-8");
			int eventType = parser.getEventType();
			List girls = new ArrayList();
			Girls girl = null;
                        //如果没有到文档的结尾就继续解析
			while(eventType != XmlPullParser.END_DOCUMENT){
                                //获取标签名字
				String data = parser.getName();
				switch (eventType) {
                                //开始标签
				case XmlPullParser.START_TAG:
					if("girl".equals(data)){
						girl = new Girls();
					}
					if("name".equals(data)){
						girl.setName(parser.nextText());
					}
					if("age".equals(data)){
						girl.setAge(Integer.parseInt(parser.nextText()));
					}
					if("school".equals(data)){
						girl.setSchool(parser.nextText());
					}
					
					break;
                                //结束标签
				case XmlPullParser.END_TAG:
					if("girl".equals(data) && girl!= null){
						girls.add(girl);
					}
					
					break;

				default:
					break;
				}
                                //手动触发事件
				eventType = parser.next();
			}
			Log.i("meng.li","size = "+girls.size());
			for(Girls g: girls){
				Log.i("meng.li","----"+g.toString()+"----");
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
	}
}
调用类 MainActivity.java

public class MainActivity extends Activity {
	private ListView listView;
	private JsonAdapter adapter;
	private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String url2 = "http://192.168.199.126:8080/Server/girls.xml";
        new XmlParse(url2).start();
    }
}




你可能感兴趣的:(Android基础)