1.介绍
SAX是一种XML解析的替代方法。相比于文档对象模型DOM,SAX是读取和操作XML数据的更快速、更轻量的方法。SAX允许您在读取文档时处理它,从而不必等待整个文档被存储之后才采取操作。它不涉及DOM所必需的开销和概念跳跃。
SAX解析XML文档采用事件驱动模式。什么是事件驱动模式?它将XML文档转换成一系列的事件,由单独的事件处理器来决定如何处理。
2.代码
SAXParserFactory saxParserFactory=SAXParserFactory.newInstance();
SAXParser saxParser=saxParserFactory.newSAXParser();
saxParser.parse(is,new DefaultHandler(){
@Override
public void startDocument() throws SAXException {
super.startDocument();
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
currentTag=localName;
if("fq".equals(localName)){
//实例化对象
fq = new FQ();
String name=attributes.getValue(0);
fq.setName(name);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
//细节:
currentTag=null;
if("fq".equals(localName)){
fqs.add(fq);
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
if("content".equals(currentTag)){
String content=new String(ch,start,length);
fq.setContent(content);
} else if("time".equals(currentTag)){
String time=new String(ch,start,length);
fq.setTime(time);
}
}
});