从NSString到NSData编码失败 [英] NSString to NSData Failing in Encoding

查看:186
本文介绍了从NSString到NSData编码失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用NSXmlParser解析ISO-8859-1数据.使用Apple自己的示例来解析ISO-8859-1,我有以下内容.

I'm trying to use NSXmlParser to parse ISO-8859-1 data. Using Apple's own example for parsing ISO-8859-1, I have the following.

// path to xml file
NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:sampleFileName ofType:@"xml"];

// string of xml contents
NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath encoding:NSUTF8StringEncoding error:nil];

NSLog(@"contents: %@", xmlFileContents);

我看到在控制台中,字符串的内容是正确的.

I see that in the console, the contents of the string is accurate.

但是,当我尝试将其转换为NSData对象(供解析器使用)时,我会执行以下操作.

However when I try to convert it to an NSData object (for use with the parser), I do the following.

NSData *xmlData = [xmlFileContents dataUsingEncoding:NSUTF8StringEncoding];

但是当我的didStartElement委托被调用时,我看到Â显示了我认为是由于编码差异引起的.

But then when my didStartElement delegate gets called, I see  showing up which I think is from an encoding discrepancy.

NSXmlParser是否可以处理ISO-8859-1,如果可以,我在做什么错了?

Can NSXmlParser handle ISO-8859-1 and if so, what am I doing wrong?

推荐答案

以防万一其他人最终陷入该线程,试图弄清楚如何以NSXmlParser正确读取以<?xml version="1.0" encoding="ISO-8859-1"?>开头的XML,这是我在干什么.

Just in case anyone else ends up on this thread trying to figure out how the heck to get XML that starts with <?xml version="1.0" encoding="ISO-8859-1"?> read properly by NSXmlParser, here is what I got working.

// path to xml file
NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:sampleFileName ofType:@"xml"];

// string of xml contents (read in NSUTF8StringEncoding)
NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath encoding:NSUTF8StringEncoding error:nil];

// interpret string of XML contents as ISO-8859-1 (NSISOLatin1StringEncoding)
NSData *xmlData = [xmlFileContents dataUsingEncoding:NSISOLatin1StringEncoding];

// spawn new thread to parse data
[NSThread detachNewThreadSelector:@selector(parseLineData:) toTarget:self withObject:xmlData];

以XML内容读取NSUTF8StringEncoding,然后以NSUTF8StringEncoding读取NSData是我避免虚假的Â字符的唯一方法.

Reading in the XML contents as NSUTF8StringEncoding and then into NSData as NSUTF8StringEncoding was the only way I avoided the spurious  characters.

这篇关于从NSString到NSData编码失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆