NSXMLParser expected result is repeated over and over and adding 1 item at time

42 views Asked by At

Im new to Objective-C and XML please help me with my simple problem.

I have this XML file.XML sample file

I want to put the parsed XML to NSDictionary. The problem is that the result is like this result

The result is repeated over and over and adding 1 item at a time.

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict {

if ([elementName isEqualToString:@"CATALOG"]) {
    self.cd = [[NSMutableArray alloc]init];
}
if ([elementName isEqualToString:@"CD"]){
    self.content = [[NSMutableDictionary alloc]init];
}

self.ElementValue = [[NSMutableString alloc] init];

for (id key in attributeDict) {
    NSLog(@"attribute %@", [attributeDict objectForKey:key]);
}

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {    

self.ElementValue = [self.ElementValue stringByAppendingString:string];

}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

if (![elementName isEqualToString:@"CD"]){
    [self.content setObject:self.ElementValue forKey:elementName];
} else {
    [self.cd addObject:self.content];
}

NSLog(@"%@",self.cd);

}
1

There are 1 answers

1
Inder Kumar Rathore On BEST ANSWER

You code seems correct, I guess you're confused with the multiple NSLog output. Which is normal since didEndElement will be called for each element. You should see your final array in parserDidEndDocument method.

Please implement parserDidEndDocument delegate method and see that your array has right number of elements

- (void)parserDidEndDocument:(NSXMLParser *)parser {
  NSLog(@"\n\n\n\n\n");
  NSLog(@"- - - - - - - - - - - - - Parsing Finished - - - - - - - - - - - - - ");
  NSLog(@"%@",self.cd);
}

Also there is little problem in your code corrected as below

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
  [self.ElementValue appendString:string];

}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
  if ([elementName isEqualToString:@"CD"]) {
    [self.cd addObject:self.content];
  }
  else if (![elementName isEqualToString:@"CATALOG"]) {
    [self.content setObject:self.ElementValue forKey:elementName];
  }
}