优点:不用事先调入整个文档,占用资源少;SAX解析器代码比DOM解析器代码小,适于Applet,下载。
缺点:不是持久的;事件过后,若没保存数据,那么数据就丢了;无状态性;从事件中只能得到文本,但不知该文本属于哪个元素;使用场合:Applet;只需XML文档的少量内容,很少回头访问;机器内存少。
import java.io.IOException;
import java.util.logging.Handler;
import javax.xml.parsers.ParserConfigurationException;
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;
public class SAX {
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
//SAXParserHandler handler = new SAXParserHandler();
parser.parse("books.xml", new SAXParserHandler());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserHandler extends DefaultHandler {
/**
* <>---------</>之间
*/
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
String value = new String(ch, start, length);
System.out.print(value.trim());
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
System.err.println("----开始解析----\n");
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
System.out.println("\n----结束解析----");
}
/**
*endElement获得</>之前内容
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if(qName!="book" && qName!="bookstore")
System.out.println("-------" + qName);
}
/**
* startElement获得标签<>内属性
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(attributes.getLength() != 0) {
System.out.print(qName + "的属性:----");
for(int i=0; i<attributes.getLength(); i++) {
System.out.print(attributes.getQName(i) + " = " + attributes.getValue(i));
System.out.println("\n");
}
}
}
}