Sax 解析:
public class SaxXml {
public static List<Person> getXml(InputStream inputStream) throws Exception {
//获取解析工厂
SAXParserFactory factory =SAXParserFactory.newInstance();
//解析器
SAXParser saxParser = factory.newSAXParser();
//实例化解析器所需要的halder对象
SaxHalder saxHalder = new SaxHalder();
//进行解析
saxParser.parse(inputStream,saxHalder);
return saxHalder.getPerList();
}
/**DefaultHandler类是SAX2事件处理程序的默认基类。它继承了EntityResolver、DTDHandler、ContentHandler和ErrorHandler这四个接口。包含这四个接口的所有方法,所以我们在编写事件处理程序时,可以不用直接实现这四个接口,而继承该类,然后重写我们需要的方法*/
}
/**
*实现了defaultHandler
*/
public class SaxHalder extends DefaultHandler {
List<Person> perList = new ArrayList<Person>();
Person person ;
String tag = "";
@Override
public void startDocument() throws SAXException {
perList = new ArrayList<Person>();
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if ("person".equals(name)) {
person = new Person();
person.setId(Integer.valueOf(attributes.getValue("id")));
}
tag = name;
}
//该方法中的ch把所解析的xml的所有数据都保存进来,且ch初始化为2K数据。 start是一个节点">"的位置.
//length就是">"到下 个"<"的长度
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String date = new String(ch,start,length);
if ("name".equals(tag)) {
person.setName(date);
}else if ("age".equals(tag)) {
person.setAge(Integer.valueOf(date));
}
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
if ("person".equals(name)) {
perList.add(person);
}
tag ="";
}
public List<Person> getPerList() {
return perList;
}
public void setPerList(List<Person> perList) {
this.perList = perList;
}
}