在android中有三种解析xml文件的方式,一种是dom解析xml,一种是sax解析xml,第三种是pull解析xml文件,第一种方式要将整个文件以树的方式读入内存,由于移动设备的内存有限,效率不高,所以很少使用,主要用到的是后两种,这篇文章主要是sax解析xml文件的详解。
我们先看项目代码:
1、先给出要解析的xml文件jindegege.xml
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="02">
<name>jindegege</name>
<age>28</age>
</person>
<person id="10">
<name>liubiyu</name>
<age>27</age>
</person>
</persons>
2、给出业务类SAXPersonService.java
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;
/**
* 采用SAX解析XML内容
*/
public class SAXPersonService {
public List<Person> getPersons(InputStream inStream)throws Exception{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
PersonParser personParser =new PersonParser();
parser.parse(inStream, personParser);
return personParser.getPersons();
}
private final class PersonParser extends DefaultHandler{
private List<Person> persons = null;
private String tag =null;
private Person person = null;
public List<Person> getPersons(){
return persons;
}
@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)){
person=new Person();
person.setId(new Integer(attributes.getValue(0)));
}
tag=localName;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
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 endElement(String uri, String localName, String qName)
throws SAXException {
if("person".equals(localName)){
persons.add(person);
person=null;
}
tag=null;
}
}
}
3、给出单元测试类
PersonServiceTest
必须继承AndroidTestCase类
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import cn.itcast.domain.Person;
import cn.itcast.service.DOMPersonService;
import cn.itcast.service.PULLPersonService;
import cn.itcast.service.SAXPersonService;
import android.content.Context;
import android.test.AndroidTestCase;
import android.util.Log;
public class PersonServiceTest extends AndroidTestCase {
private static final String TAG = "PersonServiceTest";
public void testSAXGetPersons() throws Throwable{
SAXPersonService service = new SAXPersonService();
InputStream inStream = getClass().getClassLoader().getResourceAsStream("jindegege.xml");
List<Person> persons = service.getPersons(inStream);
for(Person person : persons){
Log.i(TAG, person.toString());
}
}
public void testSave() throws Throwable{
List<Person> persons = new ArrayList<Person>();
persons.add(new Person(51, "liudehua", (short)12));
persons.add(new Person(58, "成龙", (short)32));
StringWriter writer = new StringWriter();
PULLPersonService.save(persons, writer);
Log.i(TAG, writer.toString());
}
}
4、这里因为我们建立了单元测试类,所以需要在android manifest文件中添加
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.cn" android:label="Tests for My App" />
给出代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cn"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="android.test.runner" />
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.cn" android:label="Tests for My App" />
</manifest>
5、运行单元测试方法testSAXGetPersons()
并设置好过滤器,在logcat上的结果如下: