NSXMLParser issue : don't get all my items and no data

206 views Asked by At

I have some difficulties to understand how to use NSXMLParser despite all the tutos I've watched...

I have the following XML file with for example :

<rss>
<channel>
<title>The Title</title>
<link>A URL</link>
<language>English</language>
<item>
    <name>John</name>
    <title>John4034</title>
    <city>LA</city>
    <country>USA</country>
</item>
....
<item>
    <name>Marc</name>
    <title>Marc2942</title>
    <city>London</city>
    <country>England</country>
</item>
</channel>
</rss>

I aim to stock all the items in a NSMutableArray of Item. My class Item has 4 NSString (name, title, city, country).

Here is my XMLParser.m file :

- (id) loadXMLbyURL : (NSString *) urlString
{
    items = [[NSMutableArray alloc] init];
    NSURL *url = [NSURL URLWithString:urlString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    parser = [[NSXMLParser alloc] initWithData:data];
    parser.delegate = self;
    [parser parse];
    return self;
}

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

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if([elementName isEqualToString:@"item"]) currentItem = [Item alloc];
}

- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if([elementName isEqualToString:@"name"]) [currentItem setName:currentNodeContent];
    if([elementName isEqualToString:@"title"]) [currentItem setTitle:currentNodeContent];
    if([elementName isEqualToString:@"city"]) [currentItem setCity:currentNodeContent];
    if([elementName isEqualToString:@"country"]) [currentItem setCountry:currentNodeContent];
    }
    if([elementName isEqualToString:@"item"])
    {
        [self.items addObject:currentItem];
        currentItem = nil;
        currentNodeContent = nil;
    }
}

But with all this, I have 2 issues :

  • My array of items only contains 108 indexes whereas my XML file got 299.
  • I've no data in my items properties... everything is (null) when I try to print it in the log.

Please help !

1

There are 1 answers

0
Rob On BEST ANSWER

If anybody has the same problem, I finally found the solution.

  • The problem of non-checking all the XML file was because of a PCDATA error in the XML file.
  • The problem of getting nothing in the NSStrings has been solved in this thread : NSXMLParser issue : don't get all data?