|
第一步:建立名称为xml的androidproject
第二步:建立要被读取的XML文件,在xml中右键单击src,选择File,建立名称为itcast.xml的文件,内容如下
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name>wangjiayu</name>
<age>23</age>
</person>
<person id="20">
<name>zhourui</name>
<age>20</age>
</person>
</persons>
第三步:建立一个javabean存放XML中的每一个person对象,包名称是cn.itcast.domain,类名称是Person,如下
package cn.itcast.domain;
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;
}
}
第四步:建立一个业务类,包名称是cn.itcast.service,类名称是SAXPersonService
package cn.itcast.service;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import cn.itcast.domain.Person;
public class SAXPersonService {
public List<erson> getPersons(InputStream inStream)throws Exception{ //以输入流的方式输入XML文件,以List集合返回每一个Person
SAXParserFactory factory = SAXParserFactory.newInstance(); //得到SAX解析工厂
SAXParser parser = factory.newSAXParser(); //得到SAX解析器
PersonParser personParser = new PersonParser();
/*
* 对以输入流传入的XML文件进行解析,输入流是inStream,
* 当解析遇到相应的元素节点或文本节点是就会调用相应的事件,这里是personParser
*/
parser.parse(inStream, personParser);
return personParser.getPersons();
}
private final class PersonParser extends DefaultHandler{ //DefaultHandler实现了ContentHandler
private List<Person> persons = null; //把所有的数据都存放在List集合之中
private String tag = null;
private Person person = null;
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
if(tag != null){
String data = new String(ch,start,length);
if("name".equals(tag)){
person.setName(data);
}else if("age".equals(tag)){
person.setAge(new Short(data));
}
}
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if("person".equals(localName)){
persons.add(person);
person = null;
}
tag = null;
}
public List<Person> getPersons() {
return persons;
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
persons = new ArrayList<Person>(); //当触发startDocument()方法时初始化List集合
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if("person".equals(localName)){ //判断元素是否是person
Person person = new Person();
person.setId(new Integer(attributes.getValue(0)));//为person元素的id设置值
}
tag = localName; //标记不带命名空间前缀的标签
}
}
} |
|