首页 > 代码库 > Pull解析XML
Pull解析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>
二.关键方法
public class MainActivity extends Activity { TextView content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); content = (TextView)findViewById(R.id.content); } protected void myClick(View v){ if(v.getId() == R.id.btn){ 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 { parseXmlPull(response.body().string()); } }); } private void parseXmlPull(String xmldata){ try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(new StringReader(xmldata)); int eventType = parser.getEventType(); String id = ""; String name = ""; String version = ""; while (eventType != XmlPullParser.END_DOCUMENT){ String nodeName = parser.getName(); switch (eventType){ // 开始解析节点 case XmlPullParser.START_TAG: if( "id".equals(nodeName) ){ id = parser.nextText(); }else if("name".equals(nodeName)){ name = parser.nextText(); } else if("version".equals(nodeName)){ version = parser.nextText(); } break; case XmlPullParser.END_TAG: if("app".equals(nodeName)){ Log.e("id", id); Log.e("name", name); Log.e("version", version); } break; default: break; } eventType = parser.next(); } }catch (Exception e){ e.printStackTrace(); } } }
Pull解析XML
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。