XML解析之PULL解析

来源:互联网 发布:软件调试什么意思 编辑:程序博客网 时间:2024/06/03 18:51
  以此为例
  <? 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;

原创粉丝点击