如果您希望使用 NSXMLParser 解析 XML,则需要有一个实现 NSXMLParserDelegate 的类。您可以为此使用 ViewController:
@interface ViewController : UIViewController <NSXMLParserDelegate>
然后使用此协议提供的 SAX 方法,您可以在运行时解析此 XML [XMLParser parse]
。这是您的 xml 的示例:
- (IBAction) makeRequest:(id)sender
{
NSLog(@"Making request");
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://weather.yahooapis.com/forecastrss?w=2442047&u=c"]];
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser parse];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
NSLog(@"failure with error %@",error);
}];
[operation start];
}
#pragma mark - Parsing lifecycle
- (void)startTheParsingProcess:(NSData *)parserData
{
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:parserData]; //parserData passed to NSXMLParser delegate which starts the parsing process
[parser setDelegate:self];
[parser parse]; // starts the event-driven parsing operation.
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"yweather:astronomy"])
{
NSLog(@"Sunrise: %@, Sunset: %@", [attributeDict valueForKey:@"sunrise"], [attributeDict valueForKey:@"sunset"]);
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
self.tmpInnerTagText = string; // Make a temp NSString to store the text in-between tags
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"title"])
{
NSLog(@"%@", self.tmpInnerTagText);
}
if ([elementName isEqualToString:@"description"])
{
NSLog(@"%@", self.tmpInnerTagText);
}
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
NSLog(@"Paser Error = %@", parseError);
//TODO: Create Alert message error
}
为了让 AFNetworking 支持您正在使用的 RSS xml,我必须按照以下站点的说明将“application/rss+xml”添加到可接受的内容类型中:http: //www.suushmedia.com/simple-rss-reader-with -af网络/
希望这可以帮助