NSXMLParser issue : don't get all data?

485 views Asked by At

I'm developing an application that needs to get data from an XML file. Some of the nodes have a lot of characters and I've a problem using this function :

- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

For example for the description node of an item I will get only the 20-30 last characters whereas I would get 200 or 300.

I checked this out with a NSLog and it appears the problem comes from here. Do you know what's wrong ?

Thanks for any advice.

1

There are 1 answers

3
Sergey Kalinichenko On BEST ANSWER

SAX parsers do not guarantee to get all characters at once. You may get multiple calls with chunks of characters from any given block; your code should concatenate them into a single string.

The parser object may send the delegate several parser:foundCharacters: messages to report the characters of an element. Because string may be only part of the total character content for the current element, you should append it to the current accumulation of characters until the element changes.

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    if ([qualifiedName isEqualToString:@"myTag"]) {
        buf = [NSMutableString string];
    }
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if ([qualifiedName isEqualToString:@"myTag"]) {
        buf = [buf stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSLog(@"Got %@", buf);
    }
}

- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    [buf appendString:string];
}