XmlPullParser可以解析输入流和字符串: 这是待解析的文件.
<?xml version="1.0"?> -<update> <version>2</version> <name>aiduke_Wandoujia_debug_v2_2016-07-19</name> </update>
public static void parseXMLString(String XMLString){ if (TextUtils.isEmpty(XMLString)){ throw new NullPointerException(); } XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(new StringReader(XMLString)); int event = parser.getEventType(); while(event != XmlPullParser.END_DOCUMENT){ String nodeName = parser.getName(); switch (event){ case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: if ("version".equals(nodeName)){ //版本号 long version = Long.valueOf(parser.nextText()); }else if("name".equals(nodeName)){ //apk下载地址 String name = parser.nextText(); } break; case XmlPullParser.END_DOCUMENT: break; } } } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } }
解析输入流,我们在项目里可以配合Okhttp来获取输入流进行解析:
public static void parseXMLString(InputStream is){ XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(is,null);//可以制定编码格式,可以制定为null int event = parser.getEventType(); while(event != XmlPullParser.END_DOCUMENT){ switch (event){ case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: String nodeName = parser.getName(); if ("version".equals(nodeName)){ //版本号 long version = Long.valueOf(parser.nextText()); }else if("name".equals(nodeName)){ //apk下载地址 String name = parser.nextText(); } break; case XmlPullParser.END_DOCUMENT: break; } event = parser.next(); } } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } }原文链接:/xml/294987.html