如何从android中的RSS feed XML中提取图像URL

时间:2015-05-12 14:07:08

标签: android xml rss android-xmlpullparser

目前我正在开发一个应用程序,它可以读取并显示来自RSS数据的提要,我能够解析并显示文章的标题(RSS提要是BBC新闻)和文章的描述,我也会喜欢能够为每个条目添加缩略图。

以下是XML的结构:

<item> 
  <title>Major earthquake strikes Nepal</title>  
  <description>A magnitude 7.3 earthquake strikes eastern Nepal, two weeks after a devastating quake that killed more than 8,000 people.</description>  
  <link>http://www.bbc.co.uk/news/world-asia-32701385#sa-ns_mchannel=rss&amp;ns_source=PublicRSS20-sa</link>  
  <guid isPermaLink="false">http://www.bbc.co.uk/news/world-asia-32701385</guid>  
  <pubDate>Tue, 12 May 2015 11:37:06 GMT</pubDate>  
  <media:thumbnail width="66" height="49" url="http://news.bbcimg.co.uk/media/images/82937000/jpg/_82937953_b060dce4-16b1-4c1f-8cb5-412a744930f9.jpg"/>  
  <media:thumbnail width="144" height="81" url="http://news.bbcimg.co.uk/media/images/82937000/jpg/_82937954_b060dce4-16b1-4c1f-8cb5-412a744930f9.jpg"/> 
</item>  

我需要<media:thumbnail>代码

中的网址

这是我获取标题和说明的java代码:

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)

                        title =xpp.nextText();



                } else if (xpp.getName().equalsIgnoreCase("description")) {
                    if (insideItem)
                      description = xpp.nextText();

                                         }
            } else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")) {
                insideItem = false;
                Item item = new Item(title, description, "URL HERE");

                headlines.add(item);
            }

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


        }

Item是一个包含标题,描述和URL getter和setter的类,以便在各种textview和imageview中显示数据

1 个答案:

答案 0 :(得分:0)

也许你可以使用这样的东西:

String url = "";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document document = db.parse(is);
NodeList nodeList = document.getElementsByTagName("Item");
for(int i=0; i<nodeList.getLength(); i++) {
    url = nodeList.item(i).getAttributes().getNamedItem("url").getNodeValue();
} //or if it is always only one item -> url = nodeList.item(0).getAttributes().getNamedItem("url").getNodeValue();

然后您可以将URL设置为Item对象