1>先编写一个XML文件。
<?xml version="1.0" encoding="utf-8"?>
<persons>
<person id="1">
<name>duantianlang</name>
<age>23</age>
</person>
<person id="2">
<name>wangtianba</name>
<age>33</age>
</person>
</persons>
这个没什么说的,就是个xml
2>然后先写业务层Service层。
package com.duantl.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 com.duantl.domain.Person;
/**
* SAX解析XML
* @author duantl
*
*/
public class SAXPersonService {
public List<Person> getPersons(InputStream inStream) throws Throwable{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
PersonParser personParser = new PersonParser();
parser.parse(inStream, personParser);
inStream.close();
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>JUnit测试一下
当然写JUnit的时候别忘记添加支持
<uses-library android:name="android.test.runner" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.duantl.xmlsax" android:label="Tests for My App" />
package com.duantl.xmlsax;
import java.io.InputStream;
import java.util.List;
import android.test.AndroidTestCase;
import android.util.Log;
import com.duantl.domain.Person;
import com.duantl.service.SAXPersonService;
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("persons.xml");
List<Person> persons = service.getPersons(inStream);
for(Person person : persons){
Log.i(TAG, person.toString());
}
}
}
4>测试成功