先获取到一个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",
"[email protected]"));
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("[email protected]&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
- private String pullParseXml(InputStream inputStream) {
- String result = "";
- //解析全部的xml
- boolean isParse = true;
- try {
- // 创建一个xmlPullParser的工厂
- XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
- // 获取一个解析实例
- XmlPullParser parse = factory.newPullParser();
- // 设置输入流的编码格式
- parse.setInput(inputStream, "UTF-8");
- // 当前事件的类型
- int eventType = parse.getEventType();
- while (XmlPullParser.END_DOCUMENT != eventType) {
- // 当前节点的名称
- String nodeName = parse.getName();
- switch (eventType) {
- case XmlPullParser.START_TAG:
- if ("group".equals(nodeName)) {
- // 解析<group>节点中的属性值,getAttributeCount()获取属性的个数
- for (int i = 0; i < parse.getAttributeCount(); i++) {
- // 属性名称
- String groupName = parse.getAttributeName(i);
- // 属性名称对应的值
- String nameValue = parse.getAttributeValue(i);
- result = result + groupName + " = " + nameValue;
- }
- result += "\n";
- } else if ("person".equals(nodeName)) {
- String personName = parse.getAttributeValue(0);
- String age = parse.getAttributeValue(1);
- result = result + "personName = " + personName
- + "age =" + age + "\n";
- } else if ("chinese".equals(nodeName)) {
- //节点对应的文本
- String chinese = parse.nextText();
- Pattern p = Pattern.compile("\\s*|\t|\r|\n");
- Matcher m = p.matcher(chinese);
- chinese = m.replaceAll("");
- result = result + "chinese = " + chinese;
- } else if ("english".equals(nodeName)) {
- String english = parse.nextText();
- Pattern p = Pattern.compile("\\s*|\t|\r|\n");
- Matcher m = p.matcher(english);
- english = m.replaceAll("");
- result = result + "english = " + english + "\n";
- }
- break;
- case XmlPullParser.END_TAG:
- //在解析到一个group节点完成时,退出解析xml文件
- // if("group".equals(nodeName)){
- // eventType = XmlPullParser.END_DOCUMENT;
- // isParse = false;
- // }
- break;
- default:
- break;
- }
- //整个xml文件全部解析
- if(isParse){
- eventType = parse.next();
- }
- }
- } catch (XmlPullParserException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return result;
- }
pull和sax不同最主要的体现在pull可以由客户随时终止解析xml.sax解析,只能从文档头一直读到尾,中间不能停止也不能对文件进行修改。直到解析完了整个文档才会返回。
[html] view
plaincopy
- //在解析到一个group节点完成时,退出解析xml文件
- // if("group".equals(nodeName)){
- // eventType = XmlPullParser.END_DOCUMENT;
- // isParse = false;
- // }
只要满足退出解析的条件,只需要设置如下代码即可。
[html] view
plaincopy
- eventType = XmlPullParser.END_DOCUMENT;
pull解析方式用到的方法,大部分我都在代码中注释了。
完整项目下载:http://download.csdn.net/detail/nxh_love/3978483