Cocoa 解析xml文件

苹果提供了解析xml的类,NSXMLParser及其代理NSXMLParserDelegate

 

展示一段事例代码,自己的小应用中用到的:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"question" ofType:@"xml"]; NSData *xmlData = [[NSData alloc] initWithContentsOfFile:filePath]; if (xmlData == nil) { NSLog(@"File read failed!"); } NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData]; [parser setDelegate:self]; [parser parse]; [parser release]; [xmlData release]; 

其中当前的viewController实现了NSXMLParserDelegate协议,具体实现一下几个方法:

- (void)finishedCurrentQuestion { [self.itemArray addObject:self.currentQuestion]; self.currentQuestion = nil; } #pragma mark NSXMLParserDelegate static NSString *kName_Question = @"question"; static NSString *kName_Title = @"title"; static NSString *kName_Reverse = @"reverse"; - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict { if ([elementName isEqualToString:kName_Question]) { QuestionItem *item = [[QuestionItem alloc] init]; self.currentQuestion = item; [item release]; } else if ([elementName isEqualToString:kName_Title] || [elementName isEqualToString:kName_Reverse]){ [currentString setString:@""]; storingChar = YES; } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:kName_Question]) { [self finishedCurrentQuestion]; } else if ([elementName isEqualToString:kName_Title]) { self.currentQuestion.title = currentString; } else if ([elementName isEqualToString:kName_Reverse]) { self.currentQuestion.reverse = [currentString boolValue];; } storingChar = NO; } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { //if (storingCharacters) [currentString appendString:string]; if (storingChar) { [self.currentString appendString:string]; } } - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { // Handle errors as appropriate for your application. }  

 

由此可见,NSXMLParser其实并不涉及真正的解析业务,所有的操作都在NSXMLParserDelegate中,复用性极强,代理模式的优点体现的淋漓尽致。

你可能感兴趣的:(xml,cocoa,String,File,attributes)