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

时间:2011-09-01 21:48:48

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

我正在尝试获取iPhone应用程序的天气信息。如果我输入一个5位数的邮政编码,代码就可以了。但是,我想确保如果用户没有输入有效的城市或邮政编码,它就不会崩溃。问题在于,使用Google Weather API时,XML数据会在输入有效位置时读取“城市数据”,而在“不是有效位置”时读取“problem_cause data”。请帮忙!

-(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;

    }
    }
}

1 个答案:

答案 0 :(得分:1)

结果是XML,所以使用XMLParser来查看它。在这种情况下,标准Cocoa one是NSXMLParser,然后设置一个委托,它将被调用每个元素。

对于元素的开头,您将调用parser:didStartElement:namespaceURI:qualifiedName:attributes:,这将在元素名称中传递problem_cause或forecast_information,具体取决于输入是否正常。

有关详情,请参阅Apple的Event-Driven XML Programming Guide 或者从这个Stack Exchange question

查看DOM解析器