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);
}
You code seems correct, I guess you're confused with the multiple
NSLog
output. Which is normal sincedidEndElement
will be called for each element. You should see your final array inparserDidEndDocument
method.Please implement
parserDidEndDocument
delegate method and see that your array has right number of elementsAlso there is little problem in your code corrected as below