android 用Pull 读取XML

发布时间:2017-1-18 18:01:04 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"android 用Pull 读取XML",主要涉及到android 用Pull 读取XML方面的内容,对于android 用Pull 读取XML感兴趣的同学可以参考一下。

xml文件:<?xml version="1.0" encoding="UTF-8"?> <persons> <person id="23"> <name>liming</name> <age>30</age> </person> <person id="20"> <name>zhangxiaoxiao</name> <age>25</age> </person> </persons> 模板类: public class person { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "person [id=" + id + ", name=" + name + ", age=" + age + "]"; } }读取XML代码: /** * 读取XML文件 * @param xml * @return * @throws Exception */ public List<person> getPerson(InputStream xml) throws Exception{ XmlPullParser pullPare=Xml.newPullParser(); pullPare.setInput(xml,"UTF-8"); int event=pullPare.getEventType(); person p=null; ArrayList<person> ps=null; while(event!=XmlPullParser.END_DOCUMENT) { switch(event) { case XmlPullParser.START_DOCUMENT: ps=new ArrayList<person>(); break; case XmlPullParser.START_TAG: if("person".equals(pullPare.getName())) { p=new person(); int i=Integer.parseInt(pullPare.getAttributeValue(null, "id")); p.setId(i); }else if("name".equals(pullPare.getName())) { p.setName(pullPare.nextText()); }else if("age".equals(pullPare.getName())) { p.setAge(new Short(pullPare.nextText())); } break; case XmlPullParser.END_TAG: if("person".equals(pullPare.getName())) { ps.add(p); p=null; } break; } event=pullPare.next(); } return ps; }调用读取并打印: personservice p=new personservice(); InputStream xml=this.getClass().getClassLoader().getResourceAsStream("person.xml"); try { List<person> pl=p.getPerson(xml); for(person item :pl) { Log.i("循环输出", item.toString()); } Log.i("结果", "成功"); } catch (Exception e) { // TODO Auto-generated catch block Log.i("结果", "错误"); e.printStackTrace(); }

上一篇:Java多态(利用向上向下转型和反射机理)
下一篇:ios获取设备信息-设备名称,系统名称等等

相关文章

相关评论