一个android中使用sax解析xml的例子

config.xml文件如下:

<config> <string-array name = "system_app_ti60"> <item>Browser.apk</item> <item>Phone.apk</item> <item>Contact.apk</item> <item>Settings.apk</item> <item>Gmail.apk</item> </string-array> </config>

 

用到的几个主要的类:


import org.xml.sax.Attributes;  
import org.xml.sax.SAXException;  
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.ParserConfigurationException;

 

XmlParser类:主要用于处理读取到的数据,如标签,文本等信息。

private class XmlParser extends DefaultHandler { private ArrayList<String> array = new ArrayList<String>(); String mName = null; private boolean mFound = false; public ArrayList<String> getArrayString(){ return array; } //读取到开始标签信息时回调 @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{ if(localName.equals("string-array")){ mName = attributes.getValue(0); if(mName.equals("system_app_ti60")){ mFound = true; } } } //读取到文本信息时回调 @Override public void characters(char ch [ ], int start, int length) throws SAXException{ if(mFound){ String value = new String(ch,start,length); if(!value.endsWith("apk")) return; array.add(value); } } //读取到结束标签信息时回调 @Override public void endElement(String uri, String localName, String qName) throws SAXException{ if(localName.equals("string-array")){ if(mFound){ mFound = false; } } } }

 

调用测试:

try{ SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XmlParser handler = new XmlParser(); parser.parse(new File("/system_extend/system_extend_config.xml"), handler); AppList = handler.getArrayString(); } catch(SAXException e){ Log.i("hxd","SAXException"); return; } catch(ParserConfigurationException e){ Log.i("hxd","ParserConfigurationException"); return; } catch(IOException e){ Log.i("hxd","IOException"); return; } }

 

 

 

 

 

 

 

 

你可能感兴趣的:(android,xml,String,System,import,attributes)