首页 > 代码库 > android之XML文件解析 -- SAX

android之XML文件解析 -- SAX

xml文件解析之SAX

下面的实例代码主要采用的是SAX事件驱动处理机制来解析XML文件,SAX解析XML是通过逐行扫描的方式完成的,占用内存小。dom机制是将文件全部读出,然后再以树结构的形式,来完成查找、删除等操作,对内存占用较大


MyContentHandler.java     此文件是事件处理器实现


package com.example.analysisxml;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;





public class MyContentHandler extends DefaultHandler {

String tagName;
String id,name,sex;

//获取标签的内容,标签开始和标签结束,都会调用
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
//防止标签结束后继续执行下面操作
if(tagName == null)
return;
String str = new String(ch, start, length);
if(tagName.equals("name")){
name = str;
}
else if(tagName.equals("sex")){
sex = str;
}
//System.out.println("tagName =" + tagName + ";str = " + name);
}

//文档结束时调用
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
System.out.println("-------------end------------");
}

//标签结束时调用
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
//标签结束后防止调用characters()方法执行操作
tagName = null;
if(localName.equals("worker")){
System.out.print("name = " + name);
System.out.print(" sex = " + sex);
System.out.println();
}

}

//文档开始
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();

System.out.println("-------------start------------");

}

//标签开始
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
tagName = localName;
//System.out.println("tagName =" + tagName);
if(localName.equals("worker")){
for(int i = 0;i < attributes.getLength();i++){
System.out.println(attributes.getLocalName(i) + " = " + attributes.getValue(i));
}
}
}

}

以下代码是实现调用解析xml 字符串strXML

//创建一个SAX解析工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
XMLReader reader = factory.newSAXParser().getXMLReader();


//为XMLReader设置事件处理器
reader.setContentHandler(new MyContentHandler());


//开始解析XML
reader.parse(new InputSource(new StringReader(strXML)));



XML文件的格式如下:
<workers>
<worker id="001">
<name>same</name>
<sex>man</sex>
</worker>
<worker id="002">
<name>
<sex>man</sex>
</worker>
<worker id="002">
<name>rose</name>
<sex>man</sex>
</worker>
<worker id="003">
<name>
<sex>man</sex>
</worker>
<worker id="003">
<name>jack</name>
<sex>man</sex>
</worker>
</workers>
<sex>man</sex>
</worker>
</workers>




android之XML文件解析 -- SAX