NSXMLParser can not get the content of elements co

2019-03-01 12:57发布

问题:

i have the following XMLParser but when i try to run it, it doesn't work properly.

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementname isEqualToString:@"results"])
    {
        currentJob = [SearchResult alloc];
    }

}

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


    if ([elementname isEqualToString:@"jobTitle"])
    {
        currentJob.jobTitle = currentNodeContent;
    }

    if ([elementname isEqualToString:@"location"])
    {
        currentJob.shortAddress = currentNodeContent;
    }

    if ([elementname isEqualToString:@"companyName"])
    {
        currentJob.employer = currentNodeContent;
    }

    if ([elementname isEqualToString:@"results"])
    {
        [self.jobs addObject:currentJob];
        currentJob = nil;
        currentNodeContent = nil;
    }
}

AND here is my foundCharakter Method:

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

The output doesn't start from the beginning, it starts from the middle of the String... I just can not understand, why some results look nice where some others don't.

What am i doing wrong ? How can i parse an xml properly ?

Any help will be appreciated.

Thx in advance

回答1:

I used the following code and works now:

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

     if(!elementContentString) 
     elementContentString = [[NSMutableString alloc] initWithString:string]; 
     else 
    [elementContentString appendString:string];
}


回答2:

I can suggest looking at this tutorial if you are having problem with the NSXML-parser. Hope it helps!



回答3:

I don't think there any problem in your code, it is working fine at my end. I am using the twitter api for getting xml and it is giving me proper output.