今天将XmlPullParser类学习使用了下,将解析步骤放在Log记录中,发现log中如果有存储内容为null会有异常,于是在里面多加了“1”字符串,
发现解析xml要注意连个问题
1.获取<age>23</age>
要用pullparser.nextText(). //pullparser实例化得到的当前节点
2.event = pullparser.next() //很重要,他不会自动继续向下走
下面贴出处理顺序
public List<Persion> getPersion(Reader in){ //工厂类自己实例化 // try { // XmlPullParser pullparser = XmlPullParserFactory.newInstance().newPullParser(); // } catch (XmlPullParserException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } XmlPullParser pullparser = Xml.newPullParser();//android 自带 try { pullparser.setInput(in); int event = pullparser.getEventType(); ArrayList<Persion> persons = null; Persion persion =null; if(event == pullparser.START_DOCUMENT){ persons = new ArrayList<Persion>(); }else { throw new Exception("no person"); } int i=0; while(event !=XmlPullParser.END_DOCUMENT){ //判断是否读取到文档结尾 switch(event){ case XmlPullParser.START_TAG: if("person".equals(pullparser.getName())){ persion = new Persion(); persion.setId(Integer.parseInt(pullparser.getAttributeValue(0))); }else if("age".equals(pullparser.getName())){ persion.setAge(Integer.valueOf(pullparser.nextText())); }else if("name".equals(pullparser.getName())){ persion.setName(pullparser.nextText()); } break; case XmlPullParser.END_TAG: if("person".equals(pullparser.getName())){ persons.add(persion); } break; } event = pullparser.next(); Log.i("person",pullparser.getName()+"1"); } return persons; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } //设置要解析的数据 /* * 先读到字符数组中,读到间括号,判断语法,只能自动解析第一段 */ }测试程序 Test
public class Test extends AndroidTestCase{ public void xmlRead() throws Exception { InputStream fs = this.getClass().getClassLoader().getResourceAsStream("persons.xml"); Reader re = new InputStreamReader(fs); PersonService files = new PersonService(); List<Persion> persons =files.getPersion(re); int i=0; for(Persion person:persons){ Log.i("person"+i++,person.toString()); } }
xml
<?xml version="1.0" encoding="UTF-8"?> <persons> <person id="2"> <age>23</age> <name>Tom</name> </person> <person id="3"> <age>21</age> <name>Toy</name> </person> </persons>图片为顺序处理图,
原文链接:https://www.f2er.com/xml/299846.html