Android 使用XmlPullParser解析xml

这里我们假设要解析的xml文件名为:test.xml,我们将其放在assets路径中。

xml文件内容为:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<books>
    <book id="1">
        <name>Java编程思想</name>
        <price>29.9</price>
        <date>2013年11月11日</date>
    </book>
    <book id="2">
        <name>PHP和MySQL WEB开发</name>
        <price>49.9</price>
        <date>2009年10月01日</date>
    </book>
    <book id="3">
        <name>鸟哥的Linux私房菜</name>
        <price>60.0</price>
        <date>2010年05月30日</date>
    </book>
</books>

下面的代码演示了如何去解析一个xml文件(注意assets文件流的获取方式)

  private void pullXml() {
        InputStream inputStream = null;
        List<Book> bookList = null;
        Book book = null;
        try {
            //初始化parser
            AssetManager assetManager=this.getAssets();
            inputStream = assetManager.open("test.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "utf-8");

            //开始读取数据
            int type = parser.getEventType();
            while (type != XmlPullParser.END_DOCUMENT) {//1
                switch (type) {
                    case (XmlPullParser.START_TAG)://0
                        if ("books".equals(parser.getName())) {
                            bookList = new ArrayList<Book>();
                        } else if ("book".equals(parser.getName())) {
                            book = new Book();
                            //获取book的id
                            String id = parser.getAttributeValue(0);
                            book.setId(Integer.parseInt(id));
                        } else if ("name".equals(parser.getName())) {
                            book.setName(parser.nextText());
                        } else if ("price".equals(parser.getName())) {
                            book.setPrice(Double.parseDouble(parser.nextText()));
                        } else if ("date".equals(parser.getName())) {
                            book.setDate(parser.nextText());
                        }
                        break;
          
                    case (XmlPullParser.END_TAG)://3
                        if ("book".equals(parser.getName())) {
                            bookList.add(book);
                            book = null;
                        }
                        break;
                }
                type = parser.next();
            }
        } catch (Exception e) {
            Toast.makeText(this, "解析出错", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
        Toast.makeText(this, "长度"+bookList.size(), Toast.LENGTH_LONG).show();

        for (Book book1 : bookList) {
            Log.d("book", book1.toString());
        }
    }
原文地址:https://www.cnblogs.com/wuyou/p/3418697.html