NSXMLParser can't parse special characters (accents)

走远了吗. 提交于 2019-11-30 08:59:40

I would load the url to an NSString and then convert like this.

-(id) loadXMLByURL:(NSString *)urlString{

    tickets     = [[NSMutableArray alloc] init];
    NSURL *url      = [NSURL URLWithString:urlString];
    NSError *error;
    NSString * dataString = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    parser          = [[NSXMLParser alloc] initWithData:data];
    parser.delegate = self;
    [parser parse];
    return self;

}

EDIT: Part of the problem may be that your parser:foundCharacters: method is assigning to your currentNodeContent instead of appending. See the Apple Doc at the following link.

http://developer.apple.com/library/ios/#documentation/cocoa/reference/NSXMLParserDelegate_Protocol/Reference/Reference.html

From the doc:

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.

Found the problem! It is indeed in found characters. You should change your code to this:

- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    NSLog(@"found characters: %@", string);
    if (!currentNodeContent) {
        currentNodeContent = [[NSMutableString alloc] init];
    }
    [currentNodeContent appendString:string];
}

I was having the same problem before, and the above code has fixed it.

Use

NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];

and to get the string from it, do this:

NSString *theXML = [[NSString alloc] initWithBytes:[data mutableBytes]
                                                    length:[data length]
                                                 encoding:NSUTF8StringEncoding];

Then you can parse the xml in your NSXMLParserDelegate methods.

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!