Android中解析XML一般使用SAX方式
比如Google Weather提供城市名返回天气的XML文件解析
InputStreamReader isr=new InputStreamReader(url.openStream(),"GBK");
InputSource is=new InputSource(isr);
//三步得到XMLReader对象
SAXParserFactory spf=SAXParserFactory.newInstance();
SAXParser sp=spf.newSAXParser();
XMLReader xr=sp.getXMLReader();
//设置xr对象的ContentHandler MyContentHandler继承自DefaultHandler,其中规定了解析对应XML文件的算法
xr.setContentHandler(new MyContentHandler());
xr.parse(is);
//规定XML处理规则的Handler
public class MyContentHandler extends DefaultHandler{
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
//localName代表标签的名字,attributes代表标签的属性 PS:字符串的比较用localName.equals("condition")
//进行一些逻辑判断,在对应的标签处把信息存储到要接收的对象中
}
public void endElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
}
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
}