XML Parser仅返回最后一个元素

时间:2013-03-09 18:06:48

标签: ios objective-c cocoa-touch nsxmlparser

所以我正在构建一个请求xml文件并解析它的应用程序。以下代码将名称放在标签中,其余数据放入文本视图中。现在,我在if语句中包含了一个条件,该条件计算该循环运行的次数,仅返回前两个元素。或者至少那是我应该做的。

repCount最初设为0。

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURIqualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { WeatherItem *weatherItem = [[WeatherItem alloc] init];

//Is a Location node
if ([elementName isEqualToString:@"Location"])
{

    weatherItem.name = [attributeDict objectForKey:@"name"];

    locationLabel.text = [NSString stringWithFormat:@"%@", weatherItem.name];

    NSLog(@"weatherName---> %@", weatherItem.name);

}

//Is a Rep node
if ([elementName isEqualToString:@"Rep"] && repCount  <= 1)
{

    weatherItem.winddir = [attributeDict objectForKey:@"D"];
    weatherItem.visibility = [attributeDict objectForKey:@"V"];
    weatherItem.windspeed = [attributeDict objectForKey:@"S"];
    weatherItem.temperature = [attributeDict objectForKey:@"T"];
    weatherItem.precipprob = [attributeDict objectForKey:@"Pp"];
    weatherItem.weather = [attributeDict objectForKey:@"W"];


    NSLog(@"weatherItem---> %@", weatherItem.precipprob); //easiest value to keep track of

    resultsTextView.text = [NSString stringWithFormat:
                            @"Wind Dir:%@\nVisibility:%@\nWind Speed:%@mph\nTemperature:%@C\nPrecip Prob.:%@%%\nWeather:%@\n",

                            weatherItem.winddir, weatherItem.visibility, weatherItem.windspeed,
                            weatherItem.temperature, weatherItem.precipprob, weatherItem.weather];

    repCount ++;



}

repCount = 0;}

问题是它只返回XML文件中的非常LAST元素而不是前两个元素。我会假设它遍历循环一次(repCount为0)然后将其触发到resultsTextView。再次运行它(repCount现在为1)然后将其添加到对resultsTextView触发的内容。然后停止,因为它将通过检查repCount&lt; = 1。

我错过了什么?

提前致谢。

1 个答案:

答案 0 :(得分:0)

我认为原因是你有一项任务可以在方法结束时清除repCount

repCount = 0;

repCount设置为零需要在方法外部完成 - 无论是在初始化时还是在起始文档事件处理程序中。目前,由于repCount在每个元素之后被重置,因此对于您处理的每个元素,条件的&& repCount <= 1部分仍然是正确的,因此最后一个元素的数据会覆盖已经存在的元素那之前。

repCount = 0分配移到NSXMLParserDelegate的parserDidStartDocument:方法中可以解决问题。

相关问题