SAX解析XML:SAX基本原理:采用事件驱动解析XML文件,以流式方式逐行的去读,它不需要解析完整个文档,在按内容顺序解析文档的过各中,SAX会判断当前讲到的字符是否合法XML语法中的某部分,如果符合就触发事件(例如startDocument()、endDocument()诸如此类的事件),它的特点是不会记录前面所碰到的标签,并且它是一个解析速度快并且占用内存少的XML解析器,
SAX解析步骤:1、从SAXPraserFactory中创建一个新的实例2、再从SAXParserFactory里得到一个新的SAX解析器对象SAXParser3、再调用SAXParser对象的.parse()方法里面带两个参数一个是输入流一个是DefaultHandler对象这样就可以了。而DefaultHandler是实现了ContentHandler接口的。ContentHandler接口中定义了一系列的方法事件:诸如:
- public abstract void startDocument ()
方法作用:文档解析触发此事件
- public abstract void endDocument ()
方法作用:文档解析结束时触发此事件
- public abstract void startElement (String uri, String localName, String qName, Attributes atts)
方法作用:当开始读取元素时触发此事件参数说明:
uri:命名空间
localName:不带命名空间的前缀的标签名
qName:不定期命名空间前缀的标签名
atts:得到所有的属性各和相应的值
- public abstract void endElement (String uri, String localName, String qName)
方法作用:读取的标签结束时触发此事件,参数说明同上
- public abstract void characters (char[] ch, int start, int length)
方法作用:用来处理在XML文件中读到的内容参数说明:
ch:用于存放文件的内容
start:所读到的字符串在这个数组中的起始位置
length:长度我们可以用
new String(ch,start,length)来获取内容下面以person.xml文件为例采用SAX解析器来模拟解析这个XML文档:
- <?xml version="1.0" encoding="UTF-8"?>
-
- <persons>
-
- <person id="23">
-
- <name>李明</name>
-
- <age>30</age>
-
- </person>
-
- <person id="20">
-
- <name>李向梅</name>
-
- <age>25</age>
-
- </person>
-
- </persons>
解析person.xml触发的事件为:
| 读到的标签及内容 | 触发事件 |
| {文档开始} | startDocument() |
| <persons> | startElement(, "persons", null, "{Attributes}") |
| "
" | characters("<persons>...</persons>", "12", "2") |
| <person> | startElement(, "person", null, "{Attributes}") |
| "
" | characters("<persons>...</persons>", "31", "3") |
| <name> | startElement(, "name", null, "{Attributes}") |
| "李明" | characters("<persons>...</persons>", "40", "2") |
| </name> | endElement("", "name", null) |
| "
" | characters("<persons>...</persons>", "50", "3") |
| <age> | startElement(, "age", null, "{Attributes}") |
| "30" | characters("<persons>...</persons>", "58", "2") |
| </age> | endElement("", "age", null) |
| "
" | characters("<persons>...</persons>", "67", "2") |
| </person> | endElement("", "person", null) |
| "
" | characters("<persons>...</persons>", "79", "2") |
| 又重复<person> | …. |
| {文档结束} | endDocument() |