Android 使用SAX解析XML

來源:互聯網
上載者:User

項目的結構

首先建立一個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;}@Overridepublic void startDocument() throws SAXException{bookFeed = new BookFeed();bookItem = new BookItem();}@Overridepublic 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;}@Overridepublic 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; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);feed = getFeed();showList();}private void showList() {// TODO Auto-generated method stubListView 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 exceptione.printStackTrace();}catch (SAXException e) {// TODO: handle exceptione.printStackTrace();}catch (IOException e) {// TODO: handle exceptione.printStackTrace();}return null;}}

 :

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.