首页 > 代码库 > android pull 解析xml方式

android pull 解析xml方式

先获取到一个XmlPullParserFactory实例

通过实例得到XmlPullParser对象

调用XmlPullParser的setInput()方法将服务返回的XML数据设置进去开始解析

通过getEventType()可以得到当前的解析事件

While循环不断地进行解析

如果当前的解析事件不等于XmlPullParser.END_DOCUMENT,说明解析工作还没完成,调用next()方法后可以获取下一个解析事件.

在while循环中,我们通过getName()方法得到当前结点的名字,如果发现结点名字等于id…等.就调用nextText()方法来获取结点内具体的内容

pull解析xml文件,和sax和dom一样 都可以脱离android单独使用,pull和sax的原理一样,不一样的地方是pull读取xml文件后调用方法返回的是数字, 
   读取到xml的声明返回数字0 START_DOCUMENT; 
   读取到xml的结束返回数字1 END_DOCUMENT ; 
   读取到xml的开始标签返回数字2 START_TAG 
   读取到xml的结束标签返回数字3 END_TAG 
   读取到xml的文本返回数字4 TEXT 

   pull是开源的项目 源码下载地址http://www.xmlpull.org/ 

被解析的xml文档和android dom 解析xml方式 中的xml文档一样,命名为pullTest.xml.

package com.jia.networktest;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
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;
public static final int SHOW_HTTPCLIENT = 1;
private Button send_request;
private TextView responseText;
private Button btn_httpClient;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
case SHOW_HTTPCLIENT:
String m_httpClient = (String) msg.obj;
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(m_httpClient);
}
}
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send_request = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response);
btn_httpClient = (Button) findViewById(R.id.HttpClient);
send_request.setOnClickListener(this);
btn_httpClient.setOnClickListener(this);
}


@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithHttpURLConnection();
} else if (v.getId() == R.id.HttpClient) {
sendRequestWithHttpClient();
}


}


private void sendRequestWithHttpClient() {
new Thread(new Runnable() {


@Override
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://192.168.1.88:8080/jia/get_data.txt");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username",
"yao_jiawei@hotmail.com"));
params.add(new BasicNameValuePair("password", "yaowentian"));
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
params, "utf-8");
httpPost.setEntity(urlEncodedFormEntity);


HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 请求和响应都成功了
HttpEntity entity = httpResponse.getEntity();// 获取到一个HttpEntity实例
String response = EntityUtils.toString(entity, "utf-8");// 用EntityUtils.toString()这个方法将HttpEntity转换成字符串
/*
* Message message = new Message(); message.what =
* SHOW_HTTPCLIENT; // 将服务器返回的结果存放到Message中 message.obj
* = response.toString(); handler.sendMessage(message);
*/
parseXMLWithPull(response);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}


private void parseXMLWithPull(String xmlData) {
try {
// 创建一个xmlPullParser的工厂
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
// 获取一个解析实例
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(new StringReader(xmlData));
// 当前事件的类型
int eventType = xmlPullParser.getEventType();
String id = "";
String name = "";
String version = "";
while (eventType != xmlPullParser.END_DOCUMENT) {
// 当前节点的名称
String nodeName = xmlPullParser.getName();
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("jia", "id is----------------->" + id);
Log.d("jia", "name is--------------->" + name);
Log.d("jia", "version is------------>"
+ version);
}
break;
}
default:
break;
}
eventType = xmlPullParser.next();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
}).start();


}


private void sendRequestWithHttpURLConnection() {
// 开启线程来发起网络请求
new Thread(new Runnable() {


@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
out.writeBytes("username=yao_jiawei@hotmail.com&password=yaowentian");
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 (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}


}
}).start();


}


}

[html] view plaincopy
  1. private String pullParseXml(InputStream inputStream) {  
  2.         String result = "";  
  3.         //解析全部的xml  
  4.         boolean isParse = true;  
  5.         try {  
  6.             // 创建一个xmlPullParser的工厂  
  7.             XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
  8.             // 获取一个解析实例  
  9.             XmlPullParser parse = factory.newPullParser();  
  10.             // 设置输入流的编码格式  
  11.             parse.setInput(inputStream, "UTF-8");  
  12.             // 当前事件的类型  
  13.             int eventType = parse.getEventType();  
  14.             while (XmlPullParser.END_DOCUMENT != eventType) {  
  15.                 // 当前节点的名称  
  16.                 String nodeName = parse.getName();  
  17.                 switch (eventType) {  
  18.                 case XmlPullParser.START_TAG:  
  19.                     if ("group".equals(nodeName)) {  
  20.                         // 解析<group>节点中的属性值,getAttributeCount()获取属性的个数  
  21.                         for (int i = 0; i < parse.getAttributeCount(); i++) {  
  22.                             // 属性名称  
  23.                             String groupName = parse.getAttributeName(i);  
  24.                             // 属性名称对应的值  
  25.                             String nameValue = parse.getAttributeValue(i);  
  26.                             result = result + groupName + " = " + nameValue;  
  27.                         }  
  28.                         result += "\n";  
  29.                     } else if ("person".equals(nodeName)) {  
  30.                         String personName = parse.getAttributeValue(0);  
  31.                         String age = parse.getAttributeValue(1);  
  32.                         result = result + "personName = " + personName  
  33.                                 + "age =" + age + "\n";  
  34.                     } else if ("chinese".equals(nodeName)) {  
  35.                         //节点对应的文本  
  36.                         String chinese = parse.nextText();  
  37.                         Pattern p = Pattern.compile("\\s*|\t|\r|\n");  
  38.                         Matcher m = p.matcher(chinese);  
  39.                         chinese = m.replaceAll("");  
  40.   
  41.                         result = result + "chinese = " + chinese;  
  42.                     } else if ("english".equals(nodeName)) {  
  43.                         String english = parse.nextText();  
  44.   
  45.                         Pattern p = Pattern.compile("\\s*|\t|\r|\n");  
  46.                         Matcher m = p.matcher(english);  
  47.                         english = m.replaceAll("");  
  48.   
  49.                         result = result + "english = " + english + "\n";  
  50.                     }  
  51.                     break;  
  52.                 case XmlPullParser.END_TAG:  
  53.                     //在解析到一个group节点完成时,退出解析xml文件  
  54. //                  if("group".equals(nodeName)){  
  55. //                      eventType = XmlPullParser.END_DOCUMENT;   
  56. //                      isParse = false;  
  57. //                  }  
  58.                     break;  
  59.                 default:  
  60.                     break;  
  61.                 }  
  62.                 //整个xml文件全部解析  
  63.                 if(isParse){  
  64.                     eventType = parse.next();  
  65.                 }  
  66.             }  
  67.         } catch (XmlPullParserException e) {  
  68.             // TODO Auto-generated catch block  
  69.             e.printStackTrace();  
  70.         } catch (IOException e) {  
  71.             // TODO Auto-generated catch block  
  72.             e.printStackTrace();  
  73.         }  
  74.   
  75.         return result;  
  76.     }  

pull和sax不同最主要的体现在pull可以由客户随时终止解析xml.sax解析,只能从文档头一直读到尾,中间不能停止也不能对文件进行修改。直到解析完了整个文档才会返回。

[html] view plaincopy
  1. //在解析到一个group节点完成时,退出解析xml文件  
  2. //                  if("group".equals(nodeName)){  
  3. //                      eventType = XmlPullParser.END_DOCUMENT;   
  4. //                      isParse = false;  
  5. //                  }  

只要满足退出解析的条件,只需要设置如下代码即可。

[html] view plaincopy
  1. eventType = XmlPullParser.END_DOCUMENT;   

pull解析方式用到的方法,大部分我都在代码中注释了。


完整项目下载:http://download.csdn.net/detail/nxh_love/3978483


android pull 解析xml方式