除了我的另一个答案,它使用了一些辅助类,并假设你正在存储的东西与核心数据,这是一个纯NSXMLParser的方式来做到这一点。
在这个例子中,我假设你有三个UIImageView设置标签(100,101,102),所以我们可以访问它们。首先,启动解析器代码:
// Set the URL with the images, and escape it for creating NSURL
NSString *rssURLString = @"http://feeds.gettyimages.com/channels/RecentEditorialEntertainment.rss";
NSString *escapedURL = [rssURLString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *rssURL = [NSURL URLWithString:escapedURL];
// rssParser is an NSXMLParser instance variable
if (rssParser) [rssParser release];
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:rssURL];
[rssParser setDelegate:self];
success = [rssParser parse]; // return value not used
此时解析开始和的NSXMLParser会发现在XML不同的开始和结束元素火了它的委托方法的调用。
在这个例子中,我只写didStartElement
方法:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
// look for an attribute called url
if ([attributeDict objectForKey:@"url"]) {
currentString = [attributeDict objectForKey:@"url"];
NSLog(@"Image URL: %@", currentString);
NSString* escapedURL = [currentString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:escapedURL]]];
UIImageView * tmpImageView = (UIImageView*)[scrollView viewWithTag:100+imageCount];
[tmpImageView setImage:image];
NSLog(@"images found: %d", imageCount);
imageCount++;
if (imageCount>2) [rssParser abortParsing];
}
}
下面我们看一下,看是否attributeDict(一个NSDictionary对象)包含一个URL属性。如果是这样,我们将它抓到currentString然后转义它,只是说它有NSURL会禁止的字符。然后我们从该URL创建一个图像,并根据标签号码设置适当的UIImageView图像。 imageCount是一个计数器;一旦我们完成了三张图片,我们就告诉NSXMLParser放弃解析XML。
如果你的XML会将URL元素标签内,如:
<image>http://example.com/image.jpg</image>
你需要做更多的工作与didEndElement
和foundCharacters
。看到相当优秀的Introduction to Event-Driven XML Programming Guide for Cocoa。
我敲了一个快速和肮脏的应用程序来演示这个,你可以抓住它here。
来源
2010-05-18 18:24:01
hjd
URL是动态的,因为我使用的是feedburner,这可以与“any”rss feed一起使用吗?谢谢! – 2010-03-19 20:47:58
不确定你的意思是'网址是动态的'。但只要在xml文档中有一个标签来标识图像url,就应该适用于任何xml文档。 – Remover 2010-03-20 20:47:18
由此我的意思是所有的图像托管在不同的地方... – 2010-03-26 19:57:41