使用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(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch(msg.what){ case SHOW_RESPONSE: String response=(String) msg.obj; //在这里进行UI操作,将结果显示到界面上 responseText.setText(response); break; default: break; } } }; @Override protected 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); } @Override public 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; } @Override public void onClick(View v) { // TODO Auto-generated method stub if(v.getId()==R.id.send_request){ //sendRequestWithHttpURLConnection(); sendRequestWithHttpClient(); } } private void sendRequestWithHttpURLConnection(){ //开启线程来发起网络请求 new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub HttpURLConnection 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 block e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally{ if(connection!=null){ connection.disconnect(); } } } }).start(); } private void sendRequestWithHttpClient(){ new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try{ 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解析xml private 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(); } } }
可以看到已经将xml数据指定的内容成功解析出来了。
android界面如下所示
http://blog.csdn.net/j903829182/article/details/42463987
原文地址:http://blog.csdn.net/j903829182/article/details/42463987