SAX 解析
[功能]
1. SAX 即 org.xml.sax.helpers.DefaultHandler
2. 本例以Google Weather 为例 访问:http://www.google.com/ig/api?weather=chengdu,china
[代码]
1. 定义 WeatherSet 用于保存查询到的数据 以及 这些数据的接口
public class WeatherSet { String humidity; String city; //construct public WeatherSet(){ } public void setHumidity(String s){ humidity = s; } public String getHumidity(){ return humidity; } public void setCity(String s){ city = s; } public String getCity(){ return city; } }
2. 定制 SAX 并实现以下函数
// 根据一些字符自动回调下面函数 * 开始解析 public void startDocument() * 结束解析 public void endDocument() * 遇到元素 <tag > public void startElement(String namespaceURI, String localName, String qName, Attributes atts) * 遇到元素 </tag > public void endElement(String namespaceURI, String localName, String qName) * <tag > 与 </tag > 之间 public void characters(char ch[], int start, int length)
假设我们需要获得以下的信息:
<city data="Chengdu, Sichuan" /> <humidity data="湿度: 76%" />
所以WeatherHandlerr如下:
public class WeatherHandler extends org.xml.sax.helpers.DefaultHandler { WeatherSet weather; private boolean iteration = false; public WeatherHandler(WeatherSet set){ weather = set; } @Override // called when Handler begin public void startDocument() throws SAXException { } public void endDocument() throws SAXException { } public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (localName.equals("forecast_information")) { iteration = true; } else if(localName.equals("city")) { if(iteration == true){ String attrValue = atts.getValue("data"); weather.setCity(attrValue); iteration = false; } } if (localName.equals("current_conditions")) { iteration = true; } else if(localName.equals("humidity")) { if(iteration == true){ String attrValue = atts.getValue("data"); weather.setHumidity(attrValue); iteration = false; } } } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { } public void characters(char ch[], int start, int length) { } }
3. 如何使用 WeatherHandler
* 定义目标URL
String city = "chengdu,china"; String queryString = "http://www.google.com/ig/api?weather=" + city; URI uri = new URL(queryString.replace(" ", "%20"));
* 定义 XMLReader 并指定所需的 org.xml.sax.helpers.DefaultHandler
SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); WeatherHandler handler = new WeatherHandler(weather); xr.setContentHandler(handler);
* 开始解析目标URI
xr.parse(new InputSource(uri.openStream()));
4. 其他问题
* 权限问题:
<uses-permission android:name="android.permission.INTERNET" />
* 运行结果: