iphone - 当 XML 数据根据输入的数据返回两个不同的类别时,如何解析 XML 数据?

标签 iphone ios xml-parsing weather-api google-weather-api

我正在尝试获取 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/

相关文章:

iphone - iOS 版本之间的 setRegion 不一致吗?

ios - 在哪里可以找到 iOS App Store 收据验证的共享 secret ?

ios - 使用 CALayer 创建自定义形状的按钮

java - 如何解析 SOAP 响应?

iphone - AFJSONRequestOperation 响应延迟

ios - 更新 CoreData 对象无法正常工作

XPath 将元素中的所有文本作为一个值获取,删除换行符

ios - 将字节数据从 XML 解析转换为图像

ios - numberOfRowsInSection 大于 1 时 UITableView 崩溃

ios - 我可以使用 NSUbiquitousKeyValueStore 在 Mac 和 iOS 之间同步吗?