Pergunta

I'm trying to parse data from a Wordpress RSS feed using NSXMLR. My problem is exporting my parsed data. So far I have,

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{

    currentElement = [elementName copy];

    if ([elementName isEqualToString:@"item"]){

        currentTitle = [[NSMutableString alloc] init];
        item = [[NSMutableDictionary alloc] init];
    }

}

this class

- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{


    if ([elementName isEqualToString:@"item"]){
        [item setObject:currentTitle forKey:@"title"];
    }

    [stories addObject:item];
}


- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{

    if ([currentElement isEqualToString:@"title"]){
        [currentTitle appendString:string];
    }

}

NSMutableArray *stories; NSMutableDictionary *item;

So in ViewDidLoad implementation, I have

//declare the object of allocated variable
NSData *xmlData=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"URL"]];// URL that given to parse.

//allocate memory for parser as well as
xmlParserObject =[[NSXMLParser alloc]initWithData:xmlData];
[xmlParserObject setDelegate:self];

//asking the xmlparser object to beggin with its parsing
[xmlParserObject parse];



NSLog(@"%@", [item objectForKey:@"title"]);

My problem is that I only print one object, I have multiples elements. How can I make it scan every single one of them and print them all.

Thanks in advance.

Foi útil?

Solução

If I understand your code correctly, item holds the currently parsed item, and the array stories holds all items.

So you have to allocate the stories array first:

stories = [[NSMutableArray alloc] init];

Then you do the parsing (but you should add an error check):

NSData *xmlData=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"URL"]];
xmlParserObject =[[NSXMLParser alloc]initWithData:xmlData];
[xmlParserObject setDelegate:self];
if (![xmlParserObject parse]) {
    // Parsing failed, report error...
}

And finally print the contents of the array:

for (NSDictionary *story in stories) {
    NSLog(@"%@", [story objectForKey:@"title"]);
}

The didEndElement method probably should look like this:

- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    if ([elementName isEqualToString:@"item"]){
        [item setObject:currentTitle forKey:@"title"];
        [stories addObject:item]; // <-- MOVED INTO THE IF-BLOCK
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top