android sax解析

来源:互联网 发布:linux powershell 编辑:程序博客网 时间:2024/06/06 20:44

sax解析分为两部分:

sax解析器,defaultHandler


过程:

1、从assert中读入xml文件 

InputStream inStream = this.getResources().getAssets().open("person.xml"); 

2、创建解析器

 1、获取sax解析工厂  
       SAXParserFactory  sf = SAXParserFactory.newInstance();  
 2、获取解析器  
           SAXParser sp = sf.newSAXParser();

3、编写defaultHandler

public class MyDefaulthandler extends DefaultHandler {
private HashMap<String, String> mMap = null;
private List<HashMap<String, String>> mList = null;
private String mNodeName = null;
private String currentTag = null;
private String currentValue=null;
private boolean isHasChar = true;

/**
* sax事件处理
* @param context
* @param nodeName
*/
public MyDefaulthandler(String nodeName) {
mNodeName = nodeName;
}

/**
* startDocument
*/
@Override
public void startDocument() throws SAXException {
mList = new ArrayList<HashMap<String,String>>();
}

/**
* startElement,每次读到开始标签都会执行这里
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentTag = qName;

/**
* 当读到开始标签时,如果有属性则遍历放入mMap中
*/
if(qName.equals(mNodeName)) {
mMap = new HashMap<String, String>();
isHasChar = true;
/*获取标签内的属性*/
if(attributes.getLength() > 0){
for(int i=0; i<attributes.getLength(); i++) {
mMap.put(attributes.getQName(i), attributes.getValue(i));
}
}
}
}

/**
* 读取到内容时
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String currentValue = String.valueOf(ch, start, length);
if(currentTag != null ) {
/*将获取到的\n \t剔除*/
if(currentTag.equals("name") ) {
for(int i=0; i<currentValue.length();i++) {
if(currentValue.charAt(i)=='\n' || currentValue.charAt(i)=='\t') 
isHasChar = false;
}
if(isHasChar)
mMap.put(currentTag, currentValue);
}

if(currentTag.equals("age")) {
for(int i=0; i<currentValue.length();i++) {
if(currentValue.charAt(i)=='\n' || currentValue.charAt(i)=='\t') 
isHasChar = false;
}
if(isHasChar){
mMap.put(currentTag, currentValue);
}
}
}
}

/**
* endElement
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(qName.equals(mNodeName)) {
mList.add(mMap);
currentTag = null;
currentValue = null;
mMap = null;
}
}

/**
* feedback mList
* @return
*/
public List<HashMap<String, String>> getmList() {
return mList;
}




/**
* 结束文档
*/
@Override
public void endDocument() throws SAXException {
}
}


4、将事件器defaulthandler传入

sp.parse(inStream, myHandler); 

5、获取到数组

 myHandler.getmList().


0 0