package huawei.com.service;
import huawei.com.domain.Person;
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;
/**
* 采用SAX技术解析xml内容
* @author Administrator
*
*/
public class SAXPersonService {
public List<Person> getPersons(InputStream inputStream) throws Throwable{
SAXParserFactory factory = SAXParserFactory.newInstance();//得到SAX解析器工厂
SAXParser parser = factory.newSAXParser(); //得到SAX解析器
PersonParser personParser = new PersonParser();
//第一个参数是需要解析的字节流,
//第二个参数是当遇到文档开始调用文档开始的方法,当遇到标签开始时调用startElement方法
parser.parse(inputStream, personParser);
inputStream.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 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 Integer(data));
}
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
tag= null;
if("person".equals(localName)){
persons.add(person);
person = null;
}
}
@Override
public void startDocument() throws SAXException {
persons = new ArrayList();
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
}
}
}