本文介绍在Android中采用XmlPullParser方式解析Xml节点,并将解析到的名称与值保存在Map集合中。
Xml文档结构:
<root> <result>1</result> <item> <id>1</id> <name>tiger</name> </item> </root>
XmlPullParser读取:
public Map ReadXmlData(){ String xmldoc = ""; //上面的Xml文档,以字符串表示 Map<String, String> m = new HashMap<String, String>(); XmlPullParserFactory factory; try{ factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(new ByteArrayInputStream(xmldoc.getBytes("UTF-8")), "UTF-8"); int eventType = xpp.getEventType(); while(eventType != XmlPullParser.END_DOCUMENT){ if(eventType == XmlPullParser.START_TAG){ if(xpp.getName().equals("result")) { m.put(xpp.getName(), xpp.nextText()); }else if(xpp.getName().equals("item")) { eventType = xpp.next(); while(!(eventType == XmlPullParser.END_TAG && xpp.getName().equals("item"))){ if(eventType == XmlPullParser.START_TAG) m.put(xpp.getName(), xpp.nextText()); eventType = xpp.next(); } } } eventType = xpp.next(); } }catch(Exception e){ m.put("error", e.toString()); } return m; }
遍历Map:
//m为保存的Xml节点名称及值的集合 for (Map.Entry<String, String> entry: m.entrySet()) { //key: entry.getKey //value: entry.getValue }