当前位置:编程学习 > XML/UML >>

pull解析XML文档

Xml代码 
<?xml version="1.0" encoding="UTF-8"?> 
<books> 
    <book id="12"> 
        <name>thinking in java</name> 
        <price>85.5</price> 
    </book> 
    <book id="15"> 
        <name>Spring in Action</name> 
        <price>39.0</price> 
    </book> 
</books> 
 
 
public static readLocalXml throws Exception {
                    // 创建Pull解析
                   InputStream inputStream =  getResources().openRawResource(R.raw.frist);
                   XmlPullParser pullParser= Xml.newPullParser();
                   // 解析XML
                   pullParser.setInput(inputStream, "utf-8");
                   // 开始
                   int eventType = pullParser.getEventType();
                 
                   List<Book> books = null;
                   Book book = null;
                   while (eventType != XmlPullParser.END_DOCUMENT) {
                            String nodeName = pullParser.getName();
                            switch (eventType) {
                            // 文档开始
                            case XmlPullParser.START_DOCUMENT:
                                     books = new ArrayList<Book>();
                                     break;
                            // 节点开始
                            case XmlPullParser.START_TAG:
                                     if ("book".equals(nodeName)) {
                                               book = new Book();
                                             // getAttributeValue(0) 获得节点第一个属性值
                                               book.setId(Integer
                                                                 .parseInt(pullParser.getAttributeValue(0)));
                                     } else if ("name".equals(nodeName)) {
                                               book.setName(pullParser.nextText());
                                     } else if ("price".equals(nodeName)) {
                                             //nextText 节点文本
                                               book.setPrice(Float.parseFloat(pullParser.nextText()));
                                     }
                                     break;
                            // 节点结束
                   

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,