Android 解析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") @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.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)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub News 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 stub List<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; }以上是最主要的核心代码,整个工程可以去我的资源中下载,点击下载
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。