繁体   English   中英

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

[英]How to parse XML data when it returns two different categories depending on data entered?

我正在尝试获取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,然后设置一个将为每个元素调用的委托。

对于元素的开头,您将获得parser:didStartElement:namespaceURI:qualifiedName:attributes:并且在这种情况下,这将传入元素名称,即problem_cause或Forecast_information,这取决于输入是否良好。

有关更多信息,请参阅Apple的事件驱动XML编程指南 ;或者从此Stack Exchange问​​题中查看DOM解析器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM