String tagName = xrp.getName();// 获取标签的名字
if (tagName.equals("item")) {
Map<String, String> map = new HashMap<String, String>();
String id = xrp.getAttributeValue(null, "id");// 通过属性名来获取属性值
map.put("id", id);
String url = xrp.getAttributeValue(1);// 通过属性索引来获取属性值
map.put("url", url);
map.put("name", xrp.nextText());
list.add(map);
}
}
xrp.next();// 获取解析下一个事件
}
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
三、使用Dom方式解析
基础知识:
最后来看看Dom解析方式,这种方式解析自己之前也没有用过(在j2ee开发中比较常见,没有做过这方面的东西),在Dom解析的过程中,是先把dom全部文件读入到内存中,然后使用dom的api遍历所有数据,检索想要的数据,这种方式显然是一种比较消耗内存的方式,对于像手机这样的移动设备来讲,内存是非常有限的,所以对于比较大的XML文件,不推荐使用这种方式,但是Dom也有它的优点,它比较直观,在一些方面比SAX方式比较简单。在xml文档比较小的情况下也可以考虑使用dom方式。
Dom方式解析的核心代码如下: