標籤:xml android pull 解析
使用Pull解析xml
為了測試從網上得到的資料資訊,我們需要配置一台伺服器,我使用的是tomcat6.0,怎麼配置tomcat我就不講解了。配置好了以後在apache-tomcat-6.0.39\webapps\ROOT路徑下面放置一個檔案就可以通過瀏覽器來訪問了 ,比如:放置了 一個hello.html檔案,瀏覽器進行訪問的路徑是:http://localhost:8080/hello.html
現在在root目錄下建立一個get_data.xml檔案,內容如下:
<apps> <app> <id>1</id> <name>google maps</name> <version>1.0</version> </app> <app> <id>2</id> <name>chrome</name> <version>2.1</version> </app> <app> <id>3</id> <name>google play</name> <version>2.3</version> </app></apps>
利用瀏覽器訪問,顯示如下所示:
經過上面的步驟,準備工作就已經結束了,接下來讓我們擷取並解析這段xml資料吧。
解析xml格式的資料有很多種,比較常用的是Pull和SAX解析,那麼簡單起見,我 仍然在NetworkTest項目的基礎上
繼續開發,這樣就可以重用之前網路通訊部分的代碼,從而把工作的重心放在xml資料解析上。
既然xml格式的資料已經提供好了,現在要做的就是從中解析出我們想要得到的那部分資料。修改MainActivity中的代碼:
package com.jack.networktest;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.StringReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import org.apache.http.HttpEntity;import org.apache.http.HttpHost;import org.apache.http.HttpRequest;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.ResponseHandler;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpUriRequest;import org.apache.http.conn.ClientConnectionManager;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.HttpParams;import org.apache.http.protocol.HttpContext;import org.apache.http.util.EntityUtils;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserFactory;import android.annotation.SuppressLint;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity implements OnClickListener{public static final int SHOW_RESPONSE=0;private Button sendRequest=null;private TextView responseText=null;private Handler handler=new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);switch(msg.what){case SHOW_RESPONSE:String response=(String) msg.obj;//在這裡進行UI操作,將結果顯示到介面上responseText.setText(response);break;default:break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);sendRequest=(Button) findViewById(R.id.send_request);responseText=(TextView) findViewById(R.id.response_text);sendRequest.setOnClickListener(this);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubif(v.getId()==R.id.send_request){//sendRequestWithHttpURLConnection();sendRequestWithHttpClient();}}private void sendRequestWithHttpURLConnection(){//開啟線程來發起網路請求new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubHttpURLConnection connection=null;try {URL url=new URL("http://www.baidu.com");connection =(HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(8000);connection.setReadTimeout(8000);InputStream in=connection.getInputStream();//下面對擷取到的輸入資料流進行讀取BufferedReader reader=new BufferedReader(new InputStreamReader(in));StringBuilder response=new StringBuilder();String line;while((line=reader.readLine())!=null){response.append(line);}Message message=new Message();message.what=SHOW_RESPONSE;//將伺服器返回的結果存放到Message中message.obj=response.toString();handler.sendMessage(message);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch(Exception e){e.printStackTrace();}finally{if(connection!=null){connection.disconnect();}}}}).start();}private void sendRequestWithHttpClient(){new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubtry{HttpClient httpClient=new DefaultHttpClient() ;//HttpGet httpGet=new HttpGet("http://www.baidu.com");//指定訪問的伺服器位址是電腦本機,10.0.2.2對模擬器來說就是電腦原生ip地址//8080為連接埠號碼HttpGet httpGet=new HttpGet("http://10.0.2.2:8080/get_data.xml");HttpResponse httpResponse=httpClient.execute(httpGet);if(httpResponse.getStatusLine().getStatusCode()==200){//請求和響應都成功了HttpEntity entity=httpResponse.getEntity();String response=EntityUtils.toString(entity,"utf-8");//調用parseXMLWithPull方法解析伺服器返回的資料parseXMLWithPull(response);Message message=new Message();message.what=SHOW_RESPONSE;//將伺服器返回的結果存放到Message中message.obj=response.toString();handler.sendMessage(message);}}catch(Exception e){e.printStackTrace();}}}).start();}//使用Pull解析xmlprivate void parseXMLWithPull(String xmlData){//Log.d("MainActivity", "parseXMLWithPull(String xmlData)");try{//擷取到XmlPullParserFactory的執行個體,並藉助這個執行個體得到XmlPullParser對象XmlPullParserFactory factory=XmlPullParserFactory.newInstance();XmlPullParser xmlPullParser=factory.newPullParser();//調用XmlPullParser的setInput方法將伺服器返回的xml資料設定進去開始解析xmlPullParser.setInput(new StringReader(xmlData));//通過getEventType()方法得到當前解析事件int eventType=xmlPullParser.getEventType();String id="";String name="";String version="";while(eventType!=XmlPullParser.END_DOCUMENT){//通過getName()方法得到當前節點的名字,如果發現節點名等於id、name、或version//就調用nextText()方法來擷取結點具體的內容,每當解析完一個app結點就將擷取到的內容列印出來String nodeName=xmlPullParser.getName();//Log.d("MainActivity",""+eventType+ " nodeName= "+nodeName);switch(eventType){//開始解析某個節點case XmlPullParser.START_TAG:{if("id".equals(nodeName)){id=xmlPullParser.nextText();}else if("name".equals(nodeName)){name=xmlPullParser.nextText();}else if("version".equals(nodeName)){version=xmlPullParser.nextText();}break;}case XmlPullParser.END_TAG:{if("app".equals(nodeName)){Log.d("MainActivity", "id is "+id);Log.d("MainActivity", "name is "+name);Log.d("MainActivity", "version is "+version);}break;}default:break;}//調用next()方法擷取到下一個解析事件eventType=xmlPullParser.next();}}catch(Exception e){e.printStackTrace();}}}
詳細的操作看注釋了,現在運行下程式,然後點擊send request按鈕,觀察logcat的列印日誌,:
可以看到已經將xml資料指定的內容成功解析出來了。
android介面如下所示
http://blog.csdn.net/j903829182/article/details/42463987
android學習二十一(使用Pull解析xml)