android中解析文件的三种方式

android中解析文件的三种方式
    好久没有动手写点东西了,最近在研究android的相关技术,现在就android中解析文件的三种方式做以下总结。其主要有:SAX(Simple API for XML),DOM(Document Object Model),Pull.其中前面两种和JAVA中解析XML文件方法类似,第三种解析方式则是Android自带集成的解析方式。
    SAX解析:属于事件驱动解析,先不解析整个文档,如果解析到符合XML要求的,我们则可以返回。这样解析的优势是我们不用解析整个文件,效率高。但不足是,我们无法准确的定位到解析的地方。
    DOM解析:整片文档解析。一次加载,以后就可以随处可用。优势是:以后需要什么即可以去获取,不足是:需要一次性加载解析所有的信息,时间比较久。
    PULL解析:android自带集成的解析方式,不需要第三方的jar包。其与第一种SAX解析方式类似,但是其最大的优势是我们可以解决准确的定位,即当我们解析到满足条件的就可以退出,大大提高效率。
下面以解析XML文件为例子:分别列出三种解析方式的实现代码:
XML文件为:
    person.xml
<?xml version="1.0" encoding="UTF-8"?>
<persons xmlns:pre="http://www.baidu.com">
<pre:person id="0001">
<name>clark</name>
<age>22</age>
</pre:person>
<pre:person id="0002">
<name>read</name>
<age>21</age>
</pre:person>
</persons>
//============与Person.xml 对应的model Person Object=======================
package com.example.model;
public class Person {
private Integer id;
private String name;
private short age;

public Person(){
super();
}
public Person(Integer id, String name, short age) {
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public short getAge() {
return age;
}
public void setAge(short age) {
this.age = age;
}
@Override
public String toString() {
return "id="+this.id+" name="+this.name+" age="+this.age;
}
}


第一种解析:SAX解析,需要定义一个MyContentHandler extends DefaultHandler 类
package com.example.handler;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import com.example.model.Person;
public class MyContentHandler extends DefaultHandler {
private List<Person> persons = null;
private Person person = null;
private static final String TAG = "MyContentHandler";
private String preTag = null ;
public List<Person> getPersons() {
return persons;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
/**
* ch 内容
* start 开始位置
* length 长度
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(person != null){
String data = new String(ch, start, length);
if("name".equals(preTag)){
person.setName(data);
}else if("age".equals(preTag)){
person.setAge(new Short(data));
}
}
Log.i(TAG, "开始解析内容:"+new String(ch, start, length));
}

@Override
public void endDocument() throws SAXException {
super.endDocument();
Log.i(TAG, "文档解析完毕");
}
/**
* uri 命名空间
* localName  不带命名空间前缀的标签名
* qName 带命名空间前缀的标签名
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if("person".equals(localName) && person != null){
persons.add(person);
person = null;
}
preTag = null;
Log.i(TAG, "解析完毕");
}

@Override
public void startDocument() throws SAXException {
persons = new ArrayList<Person>();
Log.i(TAG, "开始解析");
}
/**
* uri 命名空间
* localName 不带命名空间前缀的标签名
* qName  带命名空间前缀的标签名
* attributes 属性集合
*/
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if("person".equals(localName)){
person = new Person();
person.setId(new Integer(attributes.getValue("id")));
}
preTag = localName;
Log.i(TAG, "解析元素"+localName);
}
}

//=================解析需要用到的Service类===============
package com.example.service;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import com.example.handler.MyContentHandler;
import com.example.model.Person;
public class SaxPersonService {
public static List<Person> readXml(InputStream inStream) throws ParserConfigurationException, SAXException, IOException{
SAXParserFactory spf = SAXParserFactory.newInstance();
//创建解析器
SAXParser saxParse = spf.newSAXParser();
MyContentHandler handler = new MyContentHandler();
saxParse.parse(inStream, handler);
inStream.close();
return handler.getPersons();
}
}
//==================第二种DOM解析=========================
package com.example.service;
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;
import com.example.model.Person;

/**
 * DOM parse xml
 * @author Administrator
 *
 */
public class DOMPersonService {
public static List<Person> parseXml(InputStream inStream) throws Exception{
List<Person> persons = new ArrayList<Person>();
//initilization a document builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//initilization a document builder
DocumentBuilder builder = factory.newDocumentBuilder();
//use document builder to initilization a document
Document document = builder.parse(inStream);
//get xml file root node
Element root = document.getDocumentElement();
//get xml file son element
NodeList nodes = root.getElementsByTagName("pre:person");
for (int i = 0; i < nodes.getLength(); i++) {
Element personElement = (Element) nodes.item(i);
Person person = new Person();
person.setId(Integer.parseInt(personElement.getAttribute("id")));
NodeList childList = personElement.getChildNodes();
for (int j = 0; j < childList.getLength(); j++) {
Node childNode = (Node) childList.item(j);
//如果是没有子节点的node
if(childNode.getNodeType() == Node.ELEMENT_NODE){
Element childElement =(Element) childNode;
if("name".equals(childElement.getNodeName())){
person.setName(childElement.getFirstChild().getNodeValue());
}else if("age".equals(childElement.getNodeName())){
person.setAge(new Short(childElement.getFirstChild().getNodeValue()));
}
}
}
persons.add(person);
}
return persons;
}
}

//=============第三种解析方式========================
package com.example.service;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import android.util.Xml;
import com.example.model.Person;
/**
 * 
 * @author Administrator
 *
 */
public class PullPersonService {
public static List<Person> readXml(InputStream inStream) throws Exception{
List<Person> persons = null;
//get XML Pull Parse Object
XmlPullParser parse = Xml.newPullParser();
parse.setInput(inStream,"UTF-8");
//get current event type
int eventCode = parse.getEventType();
Person person = null;
while(eventCode != XmlPullParser.END_DOCUMENT){//1表示文档解析完毕
switch (eventCode) {
case XmlPullParser.START_DOCUMENT://0 表示文档开始事件
persons = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG://2表示开始元素
if("person".equals(parse.getName())){
person = new Person();
person.setId(new Integer(parse.getAttributeValue(0)));
}else if(null != person){
if("name".equals(parse.getName())){
person.setName(parse.nextText());
}else if("age".equals(parse.getName())){
person.setAge(new Short(parse.nextText()));
}
}
break;
case XmlPullParser.END_TAG://3 表示当前的Tag解析完
if("person".equals(parse.getName())&& null != person){
persons.add(person);
person = null;
}
break;
default:
break;
}
eventCode = parse.next();
}
return persons;
}
}

上一篇:/etc/resolv.conf


下一篇:Java并发编程锁之独占公平锁与非公平锁比较