我使用下面的代码来解析在线XML文件。当我运行应用程序时,我的文本字段是空的。如何从NSXMLParser中提取字符串并将它们放入IBOutlet,如文本字段,菜单项或标签?
接口文件:
#import <Foundation/Foundation.h>
@interface XMLCurrent : NSObject <NSXMLParserDelegate> {
IBOutlet NSTextField *location;
IBOutlet NSTextField *condition;
IBOutlet NSTextField *degreesF;
NSMutableString *xmlLocation;
NSMutableString *xmlWeather;
NSMutableString *xmlTempF;
}
- (void)fetchCurrentWeather:(id)sender;
@end
实施档案:
#import "XMLCurrent.h"
@implementation XMLCurrent
- (void)fetchCurrentWeather:(id)sender {
NSURL *xmlURL = [NSURL URLWithString:@"http://www.weather.gov/xml/current_obs/KCLT.xml"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[parser setDelegate:self];
[parser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqual:@"location"]) {
xmlLocation = [[NSMutableString alloc] init];
}
if ([elementName isEqual:@"weather"]) {
xmlWeather = [[NSMutableString alloc] init];
}
if ([elementName isEqual:@"temp_f"]) {
xmlTempF = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[xmlLocation appendString:string];
[xmlWeather appendString:string];
[xmlTempF appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqual:@"location"]) {
[location setStringValue:xmlLocation];
}
if ([elementName isEqual:@"weather"]) {
[condition setStringValue:xmlWeather];
}
if ([elementName isEqual:@"temp_f"]) {
[degreesF setStringValue:xmlTempF];
}
}
@end
答案 0 :(得分:0)
我认为您的问题可能有两个原因:
您在调用viewDidLoad
之前解析XML,这就是为什么所有商店都是零的
您没有在Interface Builder中连接它们。