关闭

Android的两种数据解析

标签: SAX和pull解析Android两种数据解析格式sax解析pull解析
153人阅读 评论(0) 收藏 举报
分类:

Android的两种数据解析

下面先用第一种sax解析,之后在进行pull解析,对比两种解析方式的好处
一  首先在myeclipse建立一个web项目,把person.xml复制到webRoot下,然后打开服务器,因为这个自带tomcat服务器,免费的,对我们学生而言,是个不错的选择。
例如:解析person.xml这个数据
<span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
<persons>
   <person id="1">
      <name>zhangsan</name>
      <age>20</age>
   </person>
   <person id="2">
      <name>lisi</name>
      <age>24</age>
   </person>
</persons></span>
二在Android建立项目,SAXParserDemo

MainActivity.java
<span style="font-size:14px;">package com.example.saxparserdemo;

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 java.net.URLEncoder;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.example.saxparserdemo.util.ContentHandler;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		sendRequestWithHttpURLConnection();
	}
	protected void sendRequestWithHttpURLConnection() {
		new Thread(){
			@Override
			public void run() {
				URL url;
				HttpURLConnection connection=null; 
				try {
					/*String cityName = URLEncoder.encode("滨州", "utf-8");
					System.out.println("cityName=" + cityName);
					url = new URL("http://v.juhe.cn/weather/index?format=2&cityname="+cityName+"&key=ab9d7e2007472d723baf71fcdc4ba094");*/
					url=new URL("http://10.2.5.119:8080/Server/getData.xml");
					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);
					}   	
					System.out.println("response="+response.toString());
					parseWithSax(response.toString());
					
					
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					if (connection != null) {
						connection.disconnect();
					}
				}
			}
		}.start();
			
	}
	protected void parseWithSax(String response) {
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			XMLReader xmlReader = factory.newSAXParser().getXMLReader();
			ContentHandler handler = new ContentHandler();
			// 将ContentHandler的实例设置到XMLReader中
			xmlReader.setContentHandler(handler);
			// 开始执行解析
			xmlReader.parse(new InputSource(new StringReader(response)));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}</span>
ContentHandler.java
<span style="font-size:14px;">package com.example.saxparserdemo.util;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class ContentHandler extends DefaultHandler {
	private String nodeName;
	private StringBuilder id;
	private StringBuilder name;
	private StringBuilder version;
	@Override
	public void startDocument() throws SAXException {
		id = new StringBuilder();
		name = new StringBuilder();
		version = new StringBuilder();
	}
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// 记录当前结点名
		nodeName = localName;
	}
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// 根据当前的结点名判断将内容添加到哪一个StringBuilder对象中
		if ("id".equals(nodeName)) {
			id.append(ch, start, length);
		} else if ("name".equals(nodeName)) {
			name.append(ch, start, length);
		} else if ("version".equals(nodeName)) {
			version.append(ch, start, length);
		}
	}
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if ("app".equals(localName)) {
			Log.d("ContentHandler", "id is " + id.toString().trim());
			Log.d("ContentHandler", "name is " + name.toString().trim());
			Log.d("ContentHandler", "version is " + version.toString().trim());
			// 最后要将StringBuilder清空掉
			id.setLength(0);
			name.setLength(0);
			version.setLength(0);
		}
	}
	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
	}
}</span>

第二种方法pull解析
步骤一与上面一样。
MainActivity.java
<span style="font-size:14px;">package com.example.pullparsertest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;

import com.example.pullparsertest.dao.PersonDao;
import com.example.pullparsertest.entity.Person;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendRequestWithHttpURLConnection();
        
    }

    protected void sendRequestWithHttpURLConnection() {
		new Thread(){
			@Override
			public void run() {
				URL url;
				HttpURLConnection connection=null; 
				try {
					/*String cityName = URLEncoder.encode("滨州", "utf-8");
					System.out.println("cityName=" + cityName);
					url = new URL("http://v.juhe.cn/weather/index?format=2&cityname="+cityName+"&key=ab9d7e2007472d723baf71fcdc4ba094");*/
					url=new URL("http://10.2.5.119:8080/Server/persons.xml");
					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);
					}   
					System.out.println("response="+response);
					PersonDao personDao=new PersonDao();
					List<Person> persons=personDao.getPersons(response.toString());
					System.out.println(persons);
					
					
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					if (connection != null) {
						connection.disconnect();
					}
				}
			}
		}.start();
			
	}
    
}
</span>
PersonDao.java
<span style="font-size:14px;">package com.example.pullparsertest.dao;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

import com.example.pullparsertest.entity.Person;

public class PersonDao {
   public List<Person> getPersons(String response){
	   List<Person> persons=null;
	   try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser xmlPullParser = factory.newPullParser();
			xmlPullParser.setInput(new StringReader(response));
			int eventType = xmlPullParser.getEventType();
			int id = 0;
			String name = "";
			int age = 0;
			Person person = null;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				String nodeName = xmlPullParser.getName();
				switch (eventType) {
				// 开始解析整个文档
				case XmlPullParser.START_DOCUMENT:
					persons = new ArrayList<Person>();
					break;
				// 开始解析某个结点
				case XmlPullParser.START_TAG: {
					if ("person".equals(nodeName)) {
						person = new Person();
						id = Integer.parseInt(xmlPullParser
								.getAttributeValue(0));
						person.setId(id);
					} else if ("name".equals(nodeName)) {
						name = xmlPullParser.nextText();
						person.setName(name);
					} else if ("age".equals(nodeName)) {
						age = Integer.parseInt(xmlPullParser.nextText());
						person.setAge(age);
					}

					break;
				}
				// 完成解析某个结点
				case XmlPullParser.END_TAG: {
					if ("person".equals(nodeName)) {
						persons.add(person);
						person = null;
						Log.d("MainActivity", "id is " + id);
						Log.d("MainActivity", "name is " + name);
						Log.d("MainActivity", "age is " + age);
					}
					break;
				}
				default:
					break;
				}
				eventType = xmlPullParser.next();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	   
	   return persons;
   }
} </span>

Person.java
package com.example.pullparsertest.entity;

public class Person {
    private int id;
    private String name;
    private int age;
    
	public Person() {
		super();
	}
	public Person(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	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;
	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
	
    
}
1、SAX是一个解析速度快并且占用内存少的xml解析器,非常适合用于android等移动设备,SAX全称是Simple API for Xml,既是指一种接口,也是一个软件包,作为接口,sax是事件驱动型xml解析的一个标准接口。具有如下特点1. 解析效率高,占用内存少。2.可以随时停止解析。3.不能载入整个文档到内存。4.不能写入xml5.SAX解析xml文件采用的是事件驱动。

  2、Pull解析XML文件的方式与SAX解析XML文件的方式大致相同,他们都是基于事件驱动的,页是Android中默认的解析方式,更适用于移动平台的解析方式。所以,利用pull解析XML文件需要下面几个步骤:1.通过XMLPullParserFactory获取XMLPullParser对象。2.通过XMLPullParser对象设置输入流。3.通过parser.next(),持续的解析XML文件直到文件的尾部。



主要区别:
如果在一个XML文档中我们只需要前面一部分数据,但是使用SAX方式或DOM方式会对整个文档进行解析,尽管XML文档中后面的大部分数据我们其实都不需要解析,因此这样实际上就浪费了处理资源。使用PULL方式正合适。

Pull解析器和SAX解析器虽有区别但也有相似性。他们的区别为:SAX解析器的工作方式是自动将事件推入注册的事件处理器进行处理,因此你不能控制事件的处理主动结束;而Pull解析器的工作方式为允许你的应用程序代码主动从解析器中获取事件,正因为是主动获取事件,因此可以在满足了需要的条件后不再获取事件,结束解析。这是他们主要的区别。



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:134088次
    • 积分:3083
    • 等级:
    • 排名:第11655名
    • 原创:170篇
    • 转载:28篇
    • 译文:0篇
    • 评论:9条
    博客专栏
    最新评论