0

因此,我正在构建一个请求 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 文件中的最后一个元素,而不是前两个。我会假设它运行一次循环(repCount 为 0)然后将其触发到 resultsTextView。第二次运行它(repCount 现在为 1),然后将其添加到触发到 resultsTextView 的内容中。然后它会停止,因为它将通过 repCount <= 1 的检查。

我错过了什么?

提前致谢。

4

1 回答 1

0

我认为原因是你有一个任务repCount在你的方法结束时清除了:

repCount = 0;

设置repCount为零需要在方法之外完成 - 无论是在初始化时,还是在启动文档事件处理程序中。目前,因为repCount在每个元素之后重置,所以您处理的每个&& repCount <= 1元素的条件部分都保持为真,因此最后一个元素的数据会覆盖之前的数据。

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

于 2013-03-09T18:12:52.300 回答