原理:对文档进行顺序扫描,当扫描到文档(document)开始与结束,元素开始与结束、文档结束等地方
通知事件处理函数,由事件处理函数相应动作然后继续同样的扫描,直至文档结束。
优点:消耗资源比较少;适合大文件解析;
缺点:只能读取不能修改;开发复杂。
实例:
xml
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student>
<name id="001" xx="haha">张三</name>
<sex>男</sex>
<age>20</age>
</student>
<student>
<name id="002" xx="哈哈">李四</name>
<sex>女</sex>
<age>18</age>
</student>
</students>
//
package com.java1234.xml;
import java.io.IOException;
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 sax01 extends DefaultHandler{
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
System.out.println("扫描节点开始"+new String(ch,start,length));
}
@Override
public void endDocument() throws SAXException {
System.out.println("扫描文档结束");
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("扫描元素结束" + qName);
}
@Override
public void startDocument() throws SAXException {
System.out.println("扫描文档开始");
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
System.out.println("扫描元素开始"+qName);
if(attributes!=null){
for(int i=0;i<attributes.getLength();i++){
System.out.println(attributes.getQName(i)+":"+attributes.getValue(i));
}
}
}
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory =SAXParserFactory.newInstance();
SAXParser parser= factory.newSAXParser();
parser.parse("src/NewFile.xml",new sax01());
}
}