Android Sax解析xml

来源:互联网 发布:尝试运行c windows 编辑:程序博客网 时间:2024/04/28 00:37

xml即可扩展标记语言。

可扩展标记语言,标准通用标记语言的子集,一种用于标记电子文件使其具有结构性的标记语言。
它可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。 它非常适合万维网传输,提供统一的方法来描述和交换独立于应用程序或供应商的结构化数据。
xml可以作为不同的应用程序之间的数据交换。
下面介绍一种解析xml的方法:
public class RSSL_1 extends ListActivity {private TextView mText;private String title = "";String path;private List<News> li = new ArrayList<News>();@SuppressLint("NewApi")@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.newslist);
               //下面的if 语句是屏蔽掉4.0以后主线程下载时提示的异常,也可以把下载放到handle中if (android.os.Build.VERSION.SDK_INT > 9) {        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();        StrictMode.setThreadPolicy(policy);    }mText = (TextView) findViewById(R.id.myText);Intent intent = getIntent();Bundle bundle = intent.getExtras();path = bundle.getString("path");li = getRss(path);//下载mText.setText(title);setListAdapter(new MyAdapter(getApplicationContext(), li));}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {// TODO Auto-generated method stubNews ns = li.get(position);Intent intent = new Intent();intent.setClass(RSSL_1.this, RSSL_2.class);Bundle bundle = new Bundle();bundle.putString("title", ns.get_title());bundle.putString("desc", ns.get_desc());bundle.putString("link", ns.get_link());intent.putExtras(bundle);startActivity(intent);}private List<News> getRss(String path) {// TODO Auto-generated method stubList<News> data = new ArrayList<News>();URL url = null;try {//Toast.makeText(getApplicationContext(), "正在下载", Toast.LENGTH_LONG)//.show();url = new URL(path);SAXParserFactory spf = SAXParserFactory.newInstance();//解析xml用到的类SAXParser sp = spf.newSAXParser();XMLReader xr = sp.getXMLReader();MyHandler myExampleHandler = new MyHandler();//继承defaulthandler 也是解析xml的基类xr.setContentHandler(myExampleHandler);xr.parse(new InputSource(url.openStream()));data = myExampleHandler.getParsedData();title = myExampleHandler.getRssTitle();} catch (Exception e) {Intent intent = new Intent();Bundle bundle = new Bundle();bundle.putString("error", "" + e);intent.putExtras(bundle);RSSL_1.this.setResult(99, intent);RSSL_1.this.finish();}return data;}
以上是最主要的核心代码,整个工程可以去我的资源中下载,点击下载
如有问题请留言,若转载注明出处。

2 0
原创粉丝点击