Android-pull解析
Posted 白日梦游
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android-pull解析相关的知识,希望对你有一定的参考价值。
package com.example.weekthreepull;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import com.example.adapter.MyAdapter;
import com.example.dao.BookDao;
import com.example.vo.Book;
import android.os.Bundle;
import android.app.Activity;
import android.util.Xml;
import android.view.Menu;
import android.widget.ListView;
public class MainActivity extends Activity {
List<Book> list = new ArrayList<Book>();
private Book book;
private BookDao bd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取控件
ListView lv = (ListView) findViewById(R.id.lv);
bd = new BookDao(this);
Pull();
list = bd.sel();
lv.setAdapter(new MyAdapter(this,list));
}
private void Pull() {
// 获得解析器
XmlPullParser pullParser = Xml.newPullParser();
try {
// 向解析类中添加数据源
pullParser.setInput(getAssets().open("data.xml"), "utf-8");
// 定义一个字符串变量
String tagName = null;
// 获得标签类型
int eventType = pullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
tagName = pullParser.getName();
if("book".equals(tagName)){
book = new Book();
}
break;
case XmlPullParser.TEXT:
if("name".equals(tagName)){
book.setbName(pullParser.getText());
}
else if("writer".equals(tagName)){
book.setbWriter(pullParser.getText());
}
else if("price".equals(tagName)){
book.setbPrice(Integer.parseInt(pullParser.getText()));
}
break;
case XmlPullParser.END_TAG:
tagName = pullParser.getName();
if("book".equals(tagName)){
bd.add(book);
book = null;
}
tagName = "";
break;
case XmlPullParser.END_DOCUMENT:
break;
default:
break;
}
//获得下一个标签
eventType = pullParser.next();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
以上是关于Android-pull解析的主要内容,如果未能解决你的问题,请参考以下文章