XmlPullParser能夠解析輸入流和字符串: 這是待解析的文件.node
<?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(); } }