work hard work smart

专注于Java后端开发。 不断总结,举一反三。
随笔 - 1158, 文章 - 0, 评论 - 153, 阅读 - 186万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年1月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

Android 使用SAX解析XML

Posted on   work hard work smart  阅读(243)  评论(0编辑  收藏  举报

项目的结构

首先新建一个book_info.xml的xml文件,结构如下:

<?xml version="1.0" encoding="UTF-8"?>
<books> 
  <catalog>Computer</catalog>   
  <book>
     <country>USA</country>    
    <title>Empire Burlesque</title>     
    <artist>Bob Dylan</artist>    
    <price>10.90</price>   
  </book>     
 
  <book> 
    <country>UK</country>       
   <title>Hide your heart</title>  
      <artist>Bonnie Tyler</artist>  
      <price>9.90</price>     
  </book>     
 
  <book>  
   <country>USA</country> 
    <title>Greatest Hits</title>  
     <artist>Dolly Parton</artist>   
    <price>9.90</price>   
  </book>  
</books>

 BookItem.java 代表一本书的信息,代码如下:

package com.example.utility;
 
public class BookItem {
    public String name;
    public String title;
    public String artit;
    public String price;
     
    public BookItem() {
         
    }
 
    public String getName() {  
        return name;
    }
 
    public void setName(String countryName)
    {  
        this.name = countryName;   
    }
     
    public  String getTitle() {
        return title;
    }
 
    public void setTitle(String title)
    {  
        this.title = title;
    }
     
    public  String getArtist() {
        return artit;
    }
 
    public void setArtist(String artit)
    {  
        this.artit = artit;
    }
     
    public  String getPrice() {
        return price;
    }
 
    public void setPrice(String price)
    {  
        this.price = price;
    }
}

 BookFeed代表所有书的信息,代码如下:

package com.example.utility;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
 
public class BookFeed {
    private String catalog;
    private List<BookItem> bookList;
    private int itemcount;
     
    public BookFeed()
    {
        bookList = new Vector<BookItem>(0);
    }
     
    public int addBookItem(BookItem item)
    {
        itemcount++;
        bookList.add(item);
        return itemcount;
    }
     
    public BookItem getBookItem(int location)
    {
        return bookList.get(location);
    }
     
    public List<BookItem> getAllBooks() {
        return bookList;
    }
     
    public  String getCatalog() {
        return catalog;
    }
     
 
    public void setCatalog(String catalog)
    {  
        this.catalog = catalog;
    }
     
    public  List<BookItem> getBookList() {
        return bookList;
    }
 
    public void setBookList(List<BookItem> bookList)
    {  
        this.bookList = bookList;
    }
     
    public  List GetAllBooks() {
        List<Map<String, String>> data = new ArrayList<Map<String,String>>() ;
        int size = bookList.size();
        for (int i = 0; i < size; i++) {
            HashMap<String, String> bookItemHashMap = new HashMap<String, String>();
            bookItemHashMap.put("title", bookList.get(i).getTitle());
            bookItemHashMap.put("price", bookList.get(i).getPrice());
            data.add(bookItemHashMap);
        }
         
        return data;
    }
}

 BookHand.java

package com.example.utility;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
import android.R.integer;
 
 
public class BookHandle extends DefaultHandler {
 
    BookFeed bookFeed;
    BookItem bookItem;
     
    final int Book_Country = 1;
    final int Book_Title = 2;
    final int Book_Artist = 3;
    final int Book_Price = 4;
    int curState = 0;
     
     
    public BookHandle() {
         
    }
     
    public BookFeed getBookFeed() {
        return bookFeed;
    }
     
    @Override
    public void startDocument() throws SAXException
    {
        bookFeed = new BookFeed();
        bookItem = new BookItem();
    }
     
    @Override
    public void endDocument() throws SAXException
    {
         
    }
     
     @Override 
     public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (localName.equals("books")) {
            curState = 0;  
            return;
        }
         
        if (localName.equals("book")) {
            bookItem = new BookItem();
            return;
        }
         
        if (localName.equals("country")) {
            curState = Book_Country;
            return;
        }
         
        if (localName.equals("title")) {
            curState = Book_Title;
            return;
        }
         
        if (localName.equals("artist")) {
            curState = Book_Artist;
            return;
        }
         
        if (localName.equals("price")) {
            curState = Book_Price;
            return;
        }
         
        curState = 0;
    }
     
    @Override
    public void endElement(String uri, String localName,String qName) throws SAXException
    {
        if (localName.equals("book")) {
            bookFeed.addBookItem(bookItem);
            return;
        }
    }
     
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String str = new String(ch,start,length);
        switch (curState) {
        case Book_Country:
            bookItem.setName(str);
            curState = 0;
            break;
        case Book_Title:
            bookItem.setTitle(str);
            curState = 0;
            break;
        case Book_Artist:
            bookItem.setArtist(str);
            curState = 0;
            break;
        case Book_Price:
            bookItem.setPrice(str);
            curState = 0;
            break;
 
        default:
            return;
        }
    }
     
}

 MainActiviyt.java

public class MainActivity extends Activity {
 
    public BookFeed feed;
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        feed = getFeed();
        showList();
    }
 
    private void showList() {
        // TODO Auto-generated method stub
        ListView lView = (ListView)this.findViewById(R.id.listView1);
        if (feed == null) {
            Log.i("Custom Message", "feed is null");
            return;
        }
         
        SimpleAdapter adapter = new SimpleAdapter(
                this,
                feed.GetAllBooks(),
                android.R.layout.simple_list_item_2,
                new String[]{"title","price"},
                new int[]{android.R.id.text1, android.R.id.text2});
         
        lView.setAdapter(adapter);
    }
 
    public BookFeed  getFeed() {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            BookHandle handle = new BookHandle();
            reader.setContentHandler(handle);
            InputSource iSource = new InputSource(this.getClassLoader().getResourceAsStream("book_info.xml"));
            reader.parse(iSource);
            return handle.getBookFeed();
             
        } catch (ParserConfigurationException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        catch (SAXException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
}

 效果图:

 

编辑推荐:
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
阅读排行:
· Sdcb Chats 技术博客:数据库 ID 选型的曲折之路 - 从 Guid 到自增 ID,再到
· 语音处理 开源项目 EchoSharp
· 《HelloGitHub》第 106 期
· Huawei LiteOS基于Cortex-M4 GD32F4平台移植
· mysql8.0无备份通过idb文件恢复数据过程、idb文件修复和tablespace id不一致处
点击右上角即可分享
微信分享提示