在使用 GDataXMLDocument 拼装XML 时,里面有汉字 转换为字符串时,汉字会变成"临" 这边编码, 经查阅资料 这就是ISO8859-1编码 扩展的ASCII编码。下面的方法就是讲这种单纯的编码转换成Unicode编码 ,此方法也是查阅的网上的 稍作修改。 具体转码算法 请自行查阅。
+(NSString *) changeISO88591StringToUnicodeString:(NSString *)iso88591String
{
NSMutableString *srcString = [[NSMutableString alloc]initWithString:iso88591String];
[srcString replaceOccurrencesOfString:@"&" withString:@"&" options:NSLiteralSearch range:NSMakeRange(0, [srcString length])];
[srcString replaceOccurrencesOfString:@"&#x" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [srcString length])];
NSMutableString *desString = [[NSMutableString alloc]init] ;
NSArray *arr = [srcString componentsSeparatedByString:@";"];
for(int i=0;i<[arr count]-1;i++){
NSString *v = [arr objectAtIndex:i];
char *c = malloc(3);
int value = [self changeHexStringToDec:v];
c[1] = value &0x00FF;
c[0] = value >>8 &0x00FF;
c[2] = '\0';
[desString appendString:[NSString stringWithCString:c encoding:NSUnicodeStringEncoding]];
free(c);
}
return desString;
}
+(int) changeHexStringToDec:(NSString *)strHex
{
int hexLength = [strHex length];
int ref = 0;
for (int j = 0,i = hexLength -1; i >= 0 ;i-- )
{
char a = [strHex characterAtIndex:i];
if (a == 'A') {
ref += 10*pow(16,j);
}
else if(a == 'B'){
ref += 11*pow(16,j);
}
else if(a == 'C'){
ref += 12*pow(16,j);
}
else if(a == 'D'){
ref += 13*pow(16,j);
}
else if(a == 'E'){
ref += 14*pow(16,j);
}
else if(a == 'F'){
ref += 15*pow(16,j);
}
else if(a == '0')
{
ref += 0;
}
else if(a == '1')
{
ref += 1*pow(16,j);
}
else if(a == '2')
{
ref += 2*pow(16,j);
}
else if(a == '3')
{
ref += 3*pow(16,j);
}
else if(a == '4')
{
ref += 4*pow(16,j);
}
else if(a == '5')
{
ref += 5*pow(16,j);
}
else if(a == '6')
{
ref += 6*pow(16,j);
}
else if(a == '7')
{
ref += 7*pow(16,j);
}
else if(a == '8')
{
ref += 8*pow(16,j);
}
else if(a == '9')
{
ref += 9*pow(16,j);
}
j++;
}
return ref;
}