0
votes

I have a class that implements methods from NSXMLParser and parses an XML document. Since class will be used to parse several xml documents, the keys passed into my class will change.

When I am parsing the document, I am checking the didStartElement and didEndElement match my keys and then in the foundCharacters saving the string to an NSDictionary. The NSDictionary will be returned to my delegate via a selector.

The problem is with the foundCharacters method, the string being saved is partial to that in the document.

What I am thinking is to create a NSString for each of the keys and in the foundCharacters, apending string to the dynamically created string for that key.

Here is my array.

NSArray *items = [NSArray arrayWithObjects:@"id", @"time", @"newtime", @"title", @"html", @"image", @"url", nil];

Which is passed into my parser with the following method.

-(void) parseArticles:(NSString *)url keys:(NSArray *)findKeys containingString:(NSString *)containing withDelegate:(id)aDelegate {

    keys = findKeys;
    [self setDelegate:aDelegate];

    responseData = [NSMutableData data];
    NSURL *baseUrl = [NSURL URLWithString:url];

    NSLog(@"Loading URL: %@", url);

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSURLRequest *request = [NSURLRequest requestWithURL:baseUrl];
    (void)[[NSURLConnection alloc] initWithRequest:request delegate:self];

}

Here is my foundCharacters method

-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    for(NSString *toFind in keys){
        if([currentItem isEqualToString:toFind]) [item setObject:string forKey:toFind];
    }
}
1

1 Answers

0
votes

your parser should have a NSMutableString, you should set it to empty string in didStartElement, append the string in foundCharacters and save the string into your NSDictionary in didEndElement, something like this:

-(void)parser:(NSXMLParser *)parser didStartElement...
{
     myMutableString = [[NSMutableString alloc] initWithFormat:@""];
}

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

-(void)parser:(NSXMLParser *)parser didEndElement...
{
     for(NSString *toFind in keys){
        if([currentItem isEqualToString:toFind]) [item setObject:myMutableString forKey:toFind];
    }
}