以此为例<? xml version = "1.0" encoding="UTF-8"?> <Books> <Book id="1"> <name>红楼梦</name> <price>15.3</price> <author>曹雪芹</author> </Book> <Book id="2"> <name>水浒传</name> <price>21.3</price> <author>施耐庵</author> </Book> <Book id="3"> <name>西游记</name> <price>45.0</price> <author>吴承恩</author> </Book> <Book id="4"> <name>三国演义</name> <price>25.5</price> <author>罗贯中</author> </Book> </Books>// 得到pull解析对象 XmlPullParser parser = Xml.newPullParser(); try{ // 解析xml文件 parser.setInput(getAssets().open("Books.xml"), "utf-8"); int type = parser.getEventType(); ArrayList<Book> list = null; Book book = null; // 判断是否得到文档的结尾 while (type != XmlPullParser.END_DOCUMENT) { switch (type) { case XmlPullParser.START_TAG: if ("Books".equals(parser.getName())) { list = new ArrayList<Book>(); } else if ("Book".equals(parser.getName())) { book = new Book(); } else if ("name".equals(parser.getName())) { book.setName(parser.nextText()); } else if ("price".equals(parser.getName())) { book.setPrice(parser.nextText()); } else if ("author".equals(parser.getName())) { book.setAuthor(parser.nextText()); } break; case XmlPullParser.END_TAG: if ("Book".equals(parser.getName())) list.add(book); break; default: break; } // 移动到下一行 type = parser.next(); } return list; }catch(Exception e){ e.printStackTrace(); } return null;
XML解析之PULL解析
最新推荐文章于 2018-05-27 19:46:21 发布