在iOS中使用NSXML解析数据

时间:2014-01-25 17:01:43

标签: ios objective-c nsxmlparser

我正在尝试使用NSXMLR解析来自Wordpress RSS提要的数据。我的问题是导出我的解析数据。到目前为止,我有,

- (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];
    }

}

这个班级

- (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 *故事; NSMutableDictionary * item;

所以在ViewDidLoad实现中,我有

//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"]);

我的问题是我只打印一个对象,我有多个元素。如何让它扫描每一个并打印出来。

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的代码,item会保存当前解析的项目, 数组stories包含所有项目。

所以你必须先分配stories数组:

stories = [[NSMutableArray alloc] init];

然后你进行解析(但是你应该添加一个错误检查):

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

最后打印数组的内容:

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

didEndElement方法可能应如下所示:

- (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
    }
}