android中使用SAX, DOM, 或者pull 来解析XML文档

 
<?xml version="1.0" encoding="UTF-8"?> <persons>
     <person id="1">
       <name>张三</name>
       <age>22</age>
     </person>
     <person id="2">
       <name>李四</name>
       <age>23</age>
     </person>
</persons> 


定义一个名为Person的javaBean用于存放上面解析出来的xml内容:

 

public class Person
{
    private Integer id;
    private String name;
    private Short 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;
    }
}


 

 

(1)使用SAX读取XML文件;它采用的是事件驱动,并不需要解析完整个文档,速度快并且占用内存少。需要为SAX提供实现ContentHandler接口的类。

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 com.sinber.domain.Person;
public class PersonDefaultHandler extends DefaultHandler
{
private List<Person> persons;
private Person person ; //记录当前person
private String perTag; //记录前一个标签的名称 /** * 重写父类的开始文档方法。用于初始化 */
@Override
public void startDocument()
throws SAXException {
persons = new ArrayList<Person>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if("person".equals(localName)){
Integer id = new Integer(attributes.getValue(0)); //取id
person = new Person();
person.setId(id);
}
perTag = localName;
} /**参数: * ch 整个XML字符串 * start 节点值在整个XML字符串中的索引位置 * length 节点值的长度 */
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(perTag!=null){
String data = new String(ch,start,length);
if("name".equals(perTag)){
person.setName(data);
}
else if("age".equals(perTag)){
person.setAge(new Short(data));
}
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if("person".equals(localName)){
persons.add(person);
person = null;
}
perTag = null;
}
public List<Person> getPersons() {
return persons;
}
}


 

 

SAXPerson.java

import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.sinber.domain.Person;
public class SAXPerson{
    public static List<Person> getPerson() throws Exception{        //通过类装载器获取文件
        InputStream inStream = SAXPersonService.class.getClassLoader().getResourceAsStream("person.xml");
        SAXParserFactory factory = SAXParserFactory.newInstance();
         SAXParser saxParser = factory.newSAXParser();
        PersonDefaultHandler handler = new PersonDefaultHandler();
        saxParser.parse(inStream, handler);
        inStream.close();
                return handler.getPersons();
    }
}


 

 

(2)DOM解析XML文件时,会将XML文件的所有内容读取到内存中,然后允许您使用DOM API遍历XML树、检索所需的数据。

  DOMPerson.java

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.sinber.domain.Person;
public class DOMPerson {
public static List<Person> getPerson() throws Exception{
List<Person> pers = new ArrayList<Person>();
InputStream inStream = SAXPersonService.class.getClassLoader().getResourceAsStream("person.xml");
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(inStream);
Element root = dom.getDocumentElement();
NodeList persons = root.getElementsByTagName("person");
for(int i=0;i<persons.getLength();i++){ Element personNode =(Element)persons.item(i);
Person person = new Person();
person.setId(new Integer(personNode.getAttribute("id")));
NodeList childNodes = personNode.getChildNodes();
for(int j=0;j<childNodes.getLength();
j++;
{
Node childNode = childNodes.item(j);
if(childNode.getNodeType()==Node.ELEMENT_NODE){
Element element = (Element)childNode;
if("name".equals(childNode.getNodeName())){ person.setName(new String(element.getFirstChild().getNodeValue()));
}else if("age".equals(childNode.getNodeName())){
person.setAge(new Short(element.getFirstChild().getNodeValue()));
}
}
}
pers.add(person);
}
inStream.close();
return pers;
}
}


(3)使用Pull解析器读取XML文件

  PullPerson.java

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;
import android.os.Environment;
import android.util.Xml;
import com.sinber.domain.Person;
public class PullPerson {
public static void save(List<Person> persons) throws Exception{
XmlSerializer serializer = Xml.newSerializer();
File file = new File(Environment.getExternalStorageDirectory(),"person.xml");
FileOutputStream outStream = new FileOutputStream(file);
serializer.setOutput(outStream,"UTF-8");
serializer.startDocument("UTF-8", true);
serializer.startTag("", "persons");
for(Person person:persons){
serializer.startTag("", "person"); //person serializer.attribute("", "id", ""+person.getId());
serializer.startTag("", "name"); //name
serializer.text(person.getName());
serializer.endTag("", "name"); //name serializer.startTag("", "age"); //age
serializer.text(person.getAge().toString());
serializer.endTag("", "age");//age serializer.endTag("", "person"); //person
}
serializer.endTag("", "persons");
serializer.endDocument();
outStream.close();
}
public static List<Person> getPersons() throws Exception{
List<Person> persons = null;
Person person = null;
XmlPullParser parser= Xml.newPullParser();
InputStream inStream = PullPersonService.class.getClassLoader().getResourceAsStream("person.xml");
parser.setInput(inStream, "UTF-8");
int eventType = parser.getEventType();
//触发第一个事件
while(eventType!=XmlPullParser.END_DOCUMENT){
switch(eventType){
case XmlPullParser.START_DOCUMENT: persons = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG: //开始元素事件
if("person".equals(parser.getName())){
person = new Person();
person.setId(new Integer(parser.getAttributeValue(0)));
}
else if(person!=null){
if("name".equals(parser.getName())){
person.setName(parser.nextText());
}else if("age".equals(parser.getName())){
person.setAge(new Short(parser.nextText()));
}
} break;
case
XmlPullParser.END_TAG: //结束元素事件
if("person".equals(parser.getName())){
persons.add(person);
person = null;
} break; default: break;
}
eventType = parser.next();
}
return persons;
}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值