Question

I'm very new to Objective C and Stack Overflow.I'm trying to parse an online XML document. The feed has 5 entries and each of them looks like this:

<item>
<title>the title goes here</title>
<link>http://thelink.com</link>
<guid>http://thelink.com</guid>
<category>News</category>
<description/>
<pubDate>Wed, 20 Nov 2013 20:36:00 +0430</pubDate>
<author>newsFeedAsc</author>
</item>

The top level node is:

<rss version="2.0">
<channel>
<title>feed RSS</title>
<link>Feedlink.com</link>
<description>...</description>
<language>fa-ir</language>
<pubDate/>
<lastBuildDate/>
<docs>......</docs>
<generator>.....</generator>
<ttl>5</ttl>
<image>
<title>RSS</title>
<url>
......images/ver2/rsslogo.gif
</url>
<link>.......</link>
</image>

I use the following code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *urlString=@"http://thelink.thelink/api/news?news_type=2&limit=5";
    NSURL *url = [NSURL URLWithString:urlString];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    [parser setDelegate:self];
    [parser setShouldResolveExternalEntities:NO];
    [parser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    element = elementName;
    if ([element isEqualToString:@"item"])
    {
        item    = [[NSMutableDictionary alloc] init];
        title   = [[NSMutableString alloc] init];
        link    = [[NSMutableString alloc] init];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if ([element isEqualToString:@"title"]) {
        [title appendString:string];
    } else if ([element isEqualToString:@"link"]) {
        [link appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"item"]) {
        [item setObject:title forKey:@"title"];
        [item setObject:link forKey:@"link"];
        [feeds addObject:[item copy]];
    }
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    NSLog(@"%@",feeds);
}

Now When i NSLog the "feeds" i get a null object. And When i NSLog "item" i get the last entry of the feed. If i'm not wrong, the whole XML tree should be in "feeds".

Was it helpful?

Solution

You never appear to create an instance and assign it to feeds so it doesn't exist for anything to be added to. So, when you try to add each item you're actually just throwing it away (effectively, and only when you create a new instance for the next item). And that's why you only have the last item.

So, basically, be sure to create the feeds array so you have somewhere to store the results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top