Activity部分
package lujianfei.activity11;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Activity11 extends Activity {
private Button button1;
private TextView textview1;
private EditText edittext1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
textview1 = (TextView)findViewById(R.id.textview1);
edittext1 = (EditText)findViewById(R.id.edittext1);
edittext1.setText("http://192.168.1.44/asptest/test.xml");
button1.setOnClickListener(new buttonClickListener());
}
class buttonClickListener implements OnClickListener{
public void onClick(View arg0) {
// TODO Auto-generated method stub
String url = edittext1.getText().toString();
InputStream stream = HttpUtil.GetInputStreamFromURL(url);
StringBuilder sb= new StringBuilder("");
try {
List<Person> persons= DomParser.parseXml(stream);
for(int i=0;i<persons.size();i++)
{
sb.append("id:"+persons.get(i).getId()+"\n");
sb.append("Name:"+persons.get(i).getName()+"\n");
sb.append("Age:"+persons.get(i).getAge()+"\n");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
textview1.setText(sb.toString());
}
}
}
这是核心代码部分
package lujianfei.activity11;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DomParser {
/*
* 解析xml文件,返回对象集合
* @param is xml文件的输入流
* @return 对象集合
* @throws Exception
*/
public static List parseXml(InputStream is) throws Exception{
//新建一个集合,用于存放解析后的对象
List personList = new ArrayList();
//创建对错引用
Person person = null;
//得到Dom解析对象工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//通过工厂创建Dom解析对象实例
DocumentBuilder db = factory.newDocumentBuilder();
//将xml文件的输入流交给Dom解析对象进行解析,并将Dom树返回
Document document = db.parse(is);
//通过Dom树接收到根元素
Element rootElement = document.getDocumentElement();
//通过根元素获得下属的所有名字为person节点
NodeList nodeList = rootElement.getElementsByTagName("person");
//遍历取出来的person节点集合
for(int i=0; i< nodeList.getLength(); i++){
//得到一个person节点
Element personElement = (Element)nodeList.item(i);
//新建一个Person对象
person = new Person();
//将xml标签的id属性值赋值给Person对象的Id属性
person.setId(new Integer(personElement.getAttribute("id")));
//得到person标签的下属所节点
NodeList personChildList = personElement.getChildNodes();
//循环得到的下属标签
for(int y=0; y<personChildList.getLength();y++){
//创建一个引用,指向循环的标签
Node node = personChildList.item(y);
//如果此循环出来的元素是Element对象,即标签元素,那么执行以下代码
if(Node.ELEMENT_NODE == node.getNodeType()){
//如果这个标签的名字是name,那么得到它的值,赋值给Person对象
if("name".equals(node.getNodeName())){
String nameValue = node.getFirstChild().getNodeValue();
person.setName(nameValue);
}
//如果这个标签的名字是age,那么得到它的值,赋值给Person对象
if("age".equals(node.getNodeName())){
String ageValue = node.getFirstChild().getNodeValue();
person.setAge(new Short(ageValue));
}
}
}
//将此person对象添加到personList中
personList.add(person);
//将person置空
person = null;
}
//返回xml解析后得到的对象集合
return personList;
}
}
对象定义部分
package lujianfei.activity11;
public class Person {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private int id;
private String name;
private int age;
}
实用工具类
package lujianfei.activity11;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class HttpUtil {
//通过url获得HttpGet对象
public static HttpGet getHttpGet(String url){
//实例化HttpGet
HttpGet request = new HttpGet(url);
return request;
}
//通过URL获得HttpPost对象
public static HttpPost getHttpPost(String url){
//实例化HttpPost
HttpPost request = new HttpPost(url);
return request;
}
//通过HttpGet获得HttpResponse对象
public static HttpResponse getHttpResponse(HttpGet request) throws ClientProtocolException,IOException{
//实例化HttpResponse
HttpResponse response = new DefaultHttpClient().execute(request);
return response;
}
//通过HttpPost获得HttpResponse对象
public static HttpResponse getHttpResponse(HttpPost request) throws ClientProtocolException,IOException{
//实例化HttpResponse
HttpResponse response = new DefaultHttpClient().execute(request);
return response;
}
//通过url发送post请求,返回请求结果
public static String queryStringForPost(String url){
//获得HttpPost实例
HttpPost request = HttpUtil.getHttpPost(url);
String result = null;
try{
//获得HttpResponse实例
HttpResponse response = HttpUtil.getHttpResponse(request);
//判断是否请求成功
//if(response.getStatusLine().getStatusCode() ==200){
//获得返回结果
result = EntityUtils.toString(response.getEntity());
return result;
//}
}catch(ClientProtocolException e){
e.printStackTrace();
result = "网络异常!";
return result;
}catch(IOException e){
e.printStackTrace();
result = "网络异常!";
return result;
}
//return null;
}
//通过url发送get请求,返回请求结果
public static String queryStringForGet(String url){
//获得HttpGet实例
HttpGet request = HttpUtil.getHttpGet(url);
String result = null;
try{
//获得HttpResponse实例
HttpResponse response = HttpUtil.getHttpResponse(request);
//判断是否请求成功
//if(response.getStatusLine().getStatusCode()==200){
//获得返回结果
result = EntityUtils.toString(response.getEntity());
return result;
//}
}catch(ClientProtocolException e){
e.printStackTrace();
result = "网络异常!";
return result;
}catch(IOException e){
e.printStackTrace();
result = "网络异常!";
return result;
}
//return null;
}
//通过HttpPost发送Post请求,返回请求结果
public static String queryStringForPost(HttpPost request){
String result = null;
try{
//获得HttpResponse实例
HttpResponse response = HttpUtil.getHttpResponse(request);
//判断是否请求成功
//if(response.getStatusLine().getStatusCode()==200){
//获得请求结果
result = EntityUtils.toString(response.getEntity());
return result;
//}
}catch(ClientProtocolException e){
e.printStackTrace();
result = "网络异常!";
return result;
}catch(IOException e){
e.printStackTrace();
result = "网络异常!";
return result;
}
//return null;
}
//通过HttpGet发送Get请求,返回请求结果
public static String queryStringForGet(HttpGet request){
String result = null;
try{
//获得HttpResponse实例
HttpResponse response = HttpUtil.getHttpResponse(request);
//判断是否请求成功
//if(response.getStatusLine().getStatusCode()==200){
//获得请求结果
result = EntityUtils.toString(response.getEntity());
return result;
//}
}catch(ClientProtocolException e){
e.printStackTrace();
result = "网络异常!";
return result;
}catch(IOException e){
e.printStackTrace();
result = "网络异常!";
return result;
}
//return null;
}
public static InputStream GetInputStreamFromURL(String urlstr){
HttpURLConnection connection;
URL url;
InputStream stream=null;
try{
url=new URL(urlstr);
connection =(HttpURLConnection)url.openConnection();
connection.connect();
stream = connection.getInputStream();
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e1){
e1.printStackTrace();
}
return stream;
}
}
服务器上的xml文件,我用的是asp脚本实现
<%
Dim str
Response.ContentType = "text/xml"
Response.Charset = "utf-8"
session.CodePage=65001
str ="<?xml version=""1.0"" encoding=""utf-8""?>"
str = str & ""
str = str & ""
str = str & "张三"
str = str & "31"
str = str & ""
str = str & ""
str = str & "李四"
str = str & "32"
str = str & ""
str = str & ""
Response.write(str)
%>
最后别忘了在AndroidManifest.xml的Application节点后加上这句, 要加在application之上哦