我正在尝试循环遍历Atom提要条目,并获取title属性让我们说,我找到了
this文章,我尝试了这段剪辑代码:
for (final Iterator iter = Feeds.getEntries.iterator(); iter.hasNext(); ) { element = (Element)iter.next(); key = element.getAttributeValue("href"); if ((key != null) && (key.length() > 0)) { marks.put(key,key); } //Don't have to put anything into map just syso title would be enough }
但我得到例外说:
java.lang.ClassCastException:
com.sun.syndication.Feed.synd.SyndEntryImpl
cannot be cast to org.jdom.Element at
com.emir.altantbh.FeedReader.main(FeedReader.java:47)
解决方法
SyndFeed.getEntries()
返回SyndEntryImpl列表.您无法从SyndEntryImpl强制转换为org.jdom.Element.
您可以按如下方式遍历所有SyndEntry:
for (final Iterator iter = Feed.getEntries().iterator(); iter.hasNext(); ) { final SyndEntry entry = (SyndEntry) iter.next(); String title = entry.getTitle(); String uri = entry.getUri(); //... }
API链接
> com.sun.syndication.feed.synd.SyndEntry
> com.sun.syndication.feed.synd.SyndFeed
> java.util.List
如果您使用的是Java 5.0及更高版本,也可以尝试这样做:
for (SyndEntry entry : (List<SyndEntry>) Feed.getEntries()) { String title = entry.getTitle(); String uri = entry.getUri(); //... }
这里有未经检查的强制转换,但它应该是基于getEntries()规范的安全.
也可以看看
> Java language guide/for-each loop
> Java tutorials/generics