So I'm building an app that requests an xml file and parses it. The following code puts the name in a label and the rest of the data is put into a text view. Now, I have included a condition in the if statement that counts how many times that loop has ran, only returning the first two elements. Or at least that's what I though it should do.
repCount is set to 0 initially.
- (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;}
The problem is that it only returns the very LAST element in the XML file rather than the first two. I would assume that it runs through the loop once (repCount is 0) then fires it to resultsTextView. Runs through it a second time (repCount is now 1) then adds it to what is fired to resultsTextView. It then stops as it would pass the check for repCount <= 1.
What have I missed?
Thanks in advance.
I think the reason is that you've got an assignment that clears out the repCount
at the end of your method:
repCount = 0;
Setting repCount
to zero needs to be done outside the method - either at initialization, or in the start document event handler. Currently, because repCount
is reset after each element, the && repCount <= 1
portion of your condition remains true for every element that you process, so the data for the last element overrides what's been there before.
Moving the repCount = 0
assignment into the parserDidStartDocument:
method of your NSXMLParserDelegate should fix the problem.