SAX解析xml
一.xml数据
<apps> <app> <id>1</id> <name>Google Maps</name> <version>1.0</version> </app> <app> <id>2</id> <name>Chrome</name> <version>2.1</version> </app> <app> <id>3</id> <name>Google Play</name> <version>2.3</version> </app> </apps>
二.关键代码MyContentHandler
package com.aotian.guo.saxxmldemo; import android.util.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Created by guo on 2017/4/24. */ public class MyContentHandler extends DefaultHandler { private StringBuilder id; private StringBuilder name; private StringBuilder version; private String nodeName; @Override public void startDocument() throws SAXException { id = new StringBuilder(); name = new StringBuilder(); version = new StringBuilder(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { nodeName = localName; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if( "id".equals(nodeName) ){ id.append(ch,start, length); } if( "name".equals(nodeName) ){ name.append(ch,start,length); } if("version".equals(nodeName)){ version.append(ch, start, length); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if(localName.equals("app")){ if("app".equals(localName)){ Log.e("id", id.toString().trim()); Log.e("name", name.toString().trim()); Log.e("version", version.toString().trim()); id.setLength(0); name.setLength(0); version.setLength(0); } } } @Override public void endDocument() throws SAXException { } }
三.Activity
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getXml(); } private void getXml(){ OkHttpClient http = new OkHttpClient(); final Request request = new Request.Builder() .url("http://192.168.2.100:8001/a.xml") .build(); Call call = http.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { parseXmlSax(response.body().string()); } }); } private void parseXmlSax(String xmldata){ try { SAXParserFactory factory = SAXParserFactory.newInstance(); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); MyContentHandler handler = new MyContentHandler(); // 设置实例 xmlReader.setContentHandler(handler); // 开始解析 xmlReader.parse(new InputSource(new StringReader(xmldata))); }catch (Exception e){ e.printStackTrace(); } } }