android 解析rss,将RSS feed解析为android应用

这是从URL获取RSS feed并将其在android的listview中列出的代码.

您首先需要创建一个扩展ListActivity的类,然后输入以下代码:

// Initializing instance variables

headlines = new ArrayList();

links = new ArrayList();

try {

URL url = new URL("http://www.RSS-Feed-URL-HERE");

XmlPullParserFactory factory = XmlPullParserFactory.newInstance();

factory.setNamespaceAware(false);

XmlPullParser xpp = factory.newPullParser();

// We will get the XML from an input stream

xpp.setInput(getInputStream(url), "UTF_8");

/* We will parse the XML content looking for the "

" tag which appears inside the "" tag.

* However, we should take in consideration that the rss feed name also is enclosed in a "

" tag.

* As we know, every feed begins with these lines: "Feed_Name...."

* so we should skip the "

" tag which is a child of "" tag,

* and take in consideration only "

" tag which is a child of ""

*

* In order to achieve this, we will make use of a boolean variable.

*/

boolean insideItem = false;

// Returns the type of current event: START_TAG, END_TAG, etc..

int eventType = xpp.getEventType();

while (eventType != XmlPullParser.END_DOCUMENT) {

if (eventType == XmlPullParser.START_TAG) {

if (xpp.getName().equalsIgnoreCase("item")) {

insideItem = true;

} else if (xpp.getName().equalsIgnoreCase("title")) {

if (insideItem)

headlines.add(xpp.nextText()); //extract the headline

} else if (xpp.getName().equalsIgnoreCase("link")) {

if (insideItem)

links.add(xpp.nextText()); //extract the link of article

}

}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){

insideItem=false;

}

eventType = xpp.next(); //move to next element

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (XmlPullParserException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

// Binding data

ArrayAdapter adapter = new ArrayAdapter(this,

android.R.layout.simple_list_item_1, headlines);

setListAdapter(adapter);

}

public InputStream getInputStream(URL url) {

try {

return url.openConnection().getInputStream();

} catch (IOException e) {

return null;

}

}

@Override

protected void onListItemClick(ListView l, View v, int position, long id) {

Uri uri = Uri.parse((String) links.get(position));

Intent intent = new Intent(Intent.ACTION_VIEW, uri);

startActivity(intent);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值