pull解析XML文檔 – Android移動開發技術文章_手機開發 Android移動開發教學課程

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;
                            // 節點結束
                            case XmlPullParser.END_TAG:
                                     if ("book".equals(nodeName)) {
                                               books.add(book);
                                               book = null;
                                     }
                                     break;
                            }
                            eventType = pullParser.next();
                   }
                   return books;
         }

發佈留言