• Android 使用SAX解析XML


    项目的结构

    首先新建一个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;
    	}
    }
    

     效果图:

    作者:Work Hard Work Smart
    出处:http://www.cnblogs.com/linlf03/
    欢迎任何形式的转载,未经作者同意,请保留此段声明!

  • 相关阅读:
    Postgres的TOAST技术
    Postgresql 分区表 一
    Postgresql 用户管理
    Linux FIO
    haproxy
    RHEL7/CentOS7 Network Service开机无法启动的解决方法
    Cockroachdb 四、用户管理及授权
    Cockroachdb 三、副本设置
    Cockroachdb 二、手动部署
    Cockroachdb 一、系统环境
  • 原文地址:https://www.cnblogs.com/linlf03/p/2966020.html
Copyright © 2020-2023  润新知