XML解析处理器:
/**
* 解析XML处理器
* @author zuolongsnail
*
*/
public class SAXXmlContentHandler extends DefaultHandler {
private ArrayList<Person> persons;
private Person person;
private String tagName;
public ArrayList<Person> getBooks() {
return persons;
}
@Override
public void startDocument() throws SAXException {
this.persons = new ArrayList<Person>();
Log.e("SAXXmlContentHandler", "开始解析XML文件");
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.e("SAXXmlContentHandler", "读取标签");
this.tagName = localName;
if(this.tagName.equals("person")){
person = new Person();
person.setId(Integer.parseInt(attributes.getValue(0)));
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
Log.e("SAXXmlContentHandler", "根据tagName获取标签的内容");
if (this.tagName != null) {
String data = new String(ch, start, length);
if (this.tagName.equals("name")) {
this.person.setName(data);
} else if (this.tagName.equals("age")) {
this.person.setAge(Integer.parseInt(data));
}
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equals("person")){
this.persons.add(person);
}
this.tagName = null;
}
}
persons.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>
<name>张三</name>
<age>24</age>
</person>
<person>
<name>李四</name>
<age>25</age>
</person>
<person>
<name>王五</name>
<age>26</age>
</person>
</persons>