Pull解析xml

MainActivity

public class MainActivity extends Activity {




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void btnPullResolver(View v){

        try {
            List<Book> books = pullResolverXml();
            System.out.println(books);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    private List<Book> pullResolverXml() throws Exception{
        //step1:创建pull解析器对象
        XmlPullParser parser = Xml.newPullParser();
        //参数1:你要关联度的要给文件流
        //参数2:以什么编码格式读入到计算内存当中
        InputStream is = getAssets().open("Books.xml");
        parser.setInput(is, "utf-8");//GBK  UTF-8

        int type = parser.getEventType();//读取开始文档   0 
        //创建集合
        List<Book> books = null;
        //创建一个javabean
        Book book = null;

        while(type != XmlPullParser.END_DOCUMENT){//当没有读取到文档结束位置的时候,继续循环

            switch (type) {
            case XmlPullParser.START_TAG:
                if("Books".equals(parser.getName())){
                    //创建集合
                    books = new ArrayList<Book>();
                }else if("Book".equals(parser.getName())){
                    book = new Book();
                }else if("name".equals(parser.getName())){
                    //得到name标签的文本值
                    String name = parser.nextText();
                    book.setName(name);
                }else if("price".equals(parser.getName())){
                    String price = parser.nextText();
                    book.setPrice(price);
                }else if("author".equals(parser.getName())){
                    String author = parser.nextText();
                    book.setAuthor(author);
                }
                break;

            case XmlPullParser.END_TAG:
                //当读取到Book结束标签的时候,添加到集合
                if("Book".equals(parser.getName())){
                    books.add(book);
                }
                break;
            }

            //千万不要忘记了
            type = parser.next();//往下移动一行  1
        }

        return books;

    }
}

Bean对象

public class Book {

    private String name;
    private String price;
    private String author;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    @Override
    public String toString() {
        return "Book [name=" + name + ", price=" + price + ", author=" + author
                + "]";
    }

}

猜你喜欢

转载自blog.csdn.net/peotry_favour/article/details/71079092
今日推荐