我正在尝试获取 iPhone 应用程序的天气信息。如果我输入 5 位邮政编码,则该代码有效。但是,我想确保如果用户没有输入有效的城市或邮政编码,它不会崩溃。问题在于,使用 Google Weather API 时,当输入有效地点时,XML 数据会读取“城市数据”,而当输入的地点无效时,XML 数据会读取“problem_cause 数据”。请帮忙!
-(IBAction) getlocation {
NSString *locationentered = location.text;
if ([locationentered isEqualToString: @""]) {
locationlabel.text = @"Please Enter a Location";
}
else {
NSString * locationen = locationentered;
NSString * address = @"http://www.google.com/ig/api?weather=";
NSString * request = [NSString stringWithFormat:@"%@%@",address,locationen];
NSURL * URL = [NSURL URLWithString:request];
NSError * error;
NSString* XML = [NSString stringWithContentsOfURL:URL encoding:NSASCIIStringEncoding error:&error];
NSString * temptoday = [[[[XML componentsSeparatedByString:@"city data=\""] objectAtIndex:1] componentsSeparatedByString:@"\""] objectAtIndex:0];
NSString * errorlocation = [[[[XML componentsSeparatedByString:@"problem_cause data=\""] objectAtIndex:1] componentsSeparatedByString:@"\""] objectAtIndex:0];
if ([errorlocation isEqualToString: @""]) {
locationlabel.text = @"Invalid Location";
}
if ([temptoday isEqualToString:@"(null)"]) {
locationlabel.text = @"Location present";
}
else {
locationlabel.text = temptoday;
}
}
}
最佳答案
结果是 XML,因此请使用 XMLParser 来查看它。在本例中,标准 Cocoa 是 NSXMLParser,然后设置一个委托(delegate),该委托(delegate)将为每个元素调用。
对于元素的开头,您将被称为 parser:didStartElement:namespaceURI:qualifiedName:attributes:
,在本例中,这将传入元素名称 Problem_cause 或 Forecast_information,具体取决于输入是否正确.
请参阅 Apple 的 Event-Driven XML Programming Guide了解更多 或者从这个Stack Exchange question查看DOM解析器
关于iphone - 当 XML 数据根据输入的数据返回两个不同的类别时,如何解析 XML 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7276973/