NSImage、NSData 和 NSXMLDocument 之间的文本编码问题
我正在尝试获取 NSImage 并将其转换为可以写入 XML 文档的字符串。
我当前的尝试看起来像这样:
[xmlDocument setCharacterEncoding: @"US-ASCII"];
NSData* data = [image TIFFRepresentation];
NSString* string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//Put string inside of NSXMLElement, write out NSXMLDocument.
回读看起来像这样:
NSXMLDocument* newXMLDocument = [[NSXMLDocument alloc] initWithData:data options:0 error:outError];
//Here's where it fails. I get:
//Error Domain=NSXMLParserErrorDomain Code=9 UserInfo=0x100195310 "Line 7: Char 0x0 out of allowed range"
我想我错过了一些基本的东西。这个编码问题是怎么回事?
I'm attempting to take an NSImage and convert it to a string which I can write in an XML document.
My current attempt looks something like this:
[xmlDocument setCharacterEncoding: @"US-ASCII"];
NSData* data = [image TIFFRepresentation];
NSString* string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//Put string inside of NSXMLElement, write out NSXMLDocument.
Reading back in looks something like this:
NSXMLDocument* newXMLDocument = [[NSXMLDocument alloc] initWithData:data options:0 error:outError];
//Here's where it fails. I get:
//Error Domain=NSXMLParserErrorDomain Code=9 UserInfo=0x100195310 "Line 7: Char 0x0 out of allowed range"
I assume I'm missing something basic. What's up with this encoding issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,恕我直言,在 XML 中嵌入大量二进制数据并不是一个好主意。
要回答您的问题,您需要一个支持二进制数据的编码方案,例如 Base64。
请参阅此页面,了解将任意 NSData 表示为 Base64 编码字符串的多种方法: http:// /www.cocoadev.com/index.pl?BaseSixtyFour
更新: 该页面上指向 Colloquy 的 NSData 添加的链接似乎已损坏。这是新的 URL: http://colloquy.info/project/browser/trunk /Additions/NSDataAdditions.m
First of all, embedding large amounts of binary data in XML is not a good idea, IMHO.
To answer your question, you need an encoding scheme that supports binary data, such as Base64.
See this page for more than one way to represent arbitrary NSData as a Base64-encoded string: http://www.cocoadev.com/index.pl?BaseSixtyFour
UPDATE: The link to Colloquy's NSData additions seems to be broken on that page. Here's the new URL: http://colloquy.info/project/browser/trunk/Additions/NSDataAdditions.m