由于项目要同时对应iphone和android两个平台,需要统一服务器端的配置文件,所以就有了这个xml解析器,用于解析已经做好iphone的配置文件。现在初步测试没有什么问题,不敢独享代码,特贴出来与大家分享,希望发现问题的朋友,不啬赐教。
/**
* .plist配置文件的解析器
* 支持array
* <plist version="1.0">
* <array>
* <dict>
* ...
* </dict>
* ...
* </array>
* </plist version="1.0">
*
* 支持Map
* <plist version="1.0">
* <dict>
* <id>key</id>
* <array>
* <dict>
* ...
* </dict>
* ...
* </array>
* ...
* </dict>
* </plist version="1.0">
*
* @author chen_weihua
*
*/
public class PlistHandler extends DefaultHandler {
private LinkedList<Object> list = new LinkedList<Object>();;
private boolean isRootElement = false;
private boolean keyElementBegin = false;
private String key;
private boolean valueElementBegin = false;
private Object root;
@SuppressWarnings("unchecked")
public Map getMapResult() {
return (Map)root;
}
@SuppressWarnings("unchecked")
public List getArrayResult() {
return (List)root;
}
@SuppressWarnings("unchecked")
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if ("plist".equals(localName)) {
isRootElement = true;
}
if ("dict".equals(localName)) {
if (isRootElement) {
list.addFirst(new HashMap());
isRootElement = !isRootElement;
} else {
ArrayList parent = (ArrayList)list.get(0);
list.addFirst(new HashMap());
parent.add(list.get(0));
}
}
if ("key".equals(localName)) {
keyElementBegin = true;
}
if ("true".equals(localName)) {
HashMap parent = (HashMap)list.get(0);
parent.put(key, true);
}
if ("false".equals(localName)) {
HashMap parent = (HashMap)list.get(0);
parent.put(key, false);
}
if ("array".equals(localName)) {
if (isRootElement) {
ArrayList obj = new ArrayList();
list.addFirst(obj);
isRootElement = !isRootElement;
} else {
HashMap parent = (HashMap)list.get(0);
ArrayList obj = new ArrayList();
list.addFirst(obj);
parent.put(key, obj);
}
}
if ("string".equals(localName)) {
valueElementBegin = true;
}
}
@SuppressWarnings("unchecked")
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (length > 0) {
if (keyElementBegin) {
key = new String(ch, start, length);
//Log.d("AR native", "key:" + key);
}
if (valueElementBegin) {
if (HashMap.class.equals(list.get(0).getClass())) {
HashMap parent = (HashMap)list.get(0);
String value = new String(ch, start, length);
parent.put(key, value);
} else if (ArrayList.class.equals(list.get(0).getClass())) {
ArrayList parent = (ArrayList)list.get(0);
String value = new String(ch, start, length);
parent.add(value);
}
//Log.d("AR native", "value:" + value);
}
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if ("plist".equals(localName)) {
;
}
if ("key".equals(localName)) {
keyElementBegin = false;
}
if ("string".equals(localName)) {
valueElementBegin = false;
}
if ("array".equals(localName)) {
root = list.removeFirst();
}
if ("dict".equals(localName)) {
root = list.removeFirst();
}
}
}