A problem in XML decoder of Xcode
I want to decode a xml file. The url is http://bbs.byhh.net/morecommend.xml This file is coded with gb2312. So I just transfer the coding method from gb2312 to UTF-8.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlStr = @"http://bbs.byhh.net/morecommend.xml";
[request setURL:[NSURL URLWithString:urlStr]];
[request setHTTPMethod:@"GET"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//NSLog(@"%@", returnData);
NSString *results = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:0x80000632];//gb2312 0x80000632 where the string 开发者_JAVA百科becomes null
NSString *newresults = [results stringByReplacingOccurrencesOfString:@"gb2312" withString:@"UTF-8"];
NSData *newData = [newresults dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"results=%@",new);
NSXMLParser *xmlParser = [[NSXMLParser alloc]initWithData:newData];
BOOL suc = [xmlParser parse];
if (suc == YES) {
NSLog(@"success");
}
else{
NSLog(@"fail");
}
[results release];
[request release];
The strange thing is that I indeed receive the return data. ALso I have tried to write it into a file. The file is a correct xml file with right format. But when I transfer the data into the string. The string becomes null. I don't know what is wrong.
NSString.h doesn't know anything about gb2312 or include 0x80000632 as a valid NSStringEncoding. Try using the Core Foundation equivalent to create a CFStringRef and cast it to an NSString * :
NSString *results = (NSString *)CFStringCreateWithBytes(NULL, [returnData bytes],
[returnData length], kCFStringEncodingGB_2312_80, true);
精彩评论