Android 应用软件开发(十二)XML文件解析

XML(可扩展标记语言)

解析XML文档的方式:SAX和DOM

1、DOM(Document Object Model)解析XML文档是将XML文档全部装在到内存里面解析成一棵树,

操作方便,但是当XML文档很大时,性能不好

2、SAX(Simple API for XML)是逐行扫描XML,边扫描边解析,可以随时停止

SAX原理:

就是对文档进行顺序扫描,当扫描到文档开始与结束、元素开始与结束等地方时通知时间处理函数(这些

函数都是回调函数),由事件处理函数做出相应的动作,然后继续扫描,直至文档结束。

基本的事件:

1. 文档的开始和结束时触发文档处理事件

2. 文档内每一XML元素接受解析的前后触发元素事件

3. 任何元数据通常都由单独的事件交付

4. 在处理文档的DTD或Schema时产生DTD或Schema事件

5. 产生错误事件用来通知主机应用程序解析错误

使用SAX解析文档的步骤:

1. 创建事件处理程序。

2. 创建SAX解析器。

3. 将事件处理程序分配给解析器。

4. 对文档进行解析,将每个事件发给处理程序。

SAX的常用接口:ContentHandler

void startDocument()

Receive notification of the beginning of a document.

void endDocument()

Receive notification of the end of a document.

void startElement(String uri, String localName, String qName, Attributes atts)

Receive notification of the beginning of an element.

void endElement(String uri, String localName, String qName)

Receive notification of the end of an element.

void characters(char[] ch, int start, int length)

Receive notification of character data.

下面用一小段代码说明SAX的使用

HttpDownloader hd = new HttpDownloader();
String resultStr = hd.download("http://XXX");
try{
	SAXParserFactory factory = SAXParserFactory.newInstance();
	XMLReader reader = factory.newSAXParser().getXMLReader();
	reader.setContentHandler(new MyContentHandler());
	reader.parse(new InputSource(new StringReader(resultStr)));
   }catch(Exception e){
	e.printStackTrace();
	}

其中MyContentHandler是实现的ContentHandler接口的一个类

下面重点介绍一下上面回调函数的参数:

startElement

uri
the Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed

localName
the local name (without prefix), or the empty string if Namespace processing is not being performed

qName
the qualified name (with prefix), or the empty string if qualified names are not available

atts
the attributes attached to the element. If there are no attributes, it shall be an empty Attributes object. The value of this object after startElement returns is undefined

characters

ch
the characters from the XML document

start
the start position in the array

length
the number of characters to read from the array

以上主要是分析解析一个XML文件的步骤和相应的方法,后续将补充一个完整的代码解析一个XML文档

posted @ 2011-11-08 22:13  哈哈开心  阅读(570)  评论(0编辑  收藏  举报