Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为XML编码RTFD_Xml_Cocoa_Rtf_Nsattributedstring - Fatal编程技术网

为XML编码RTFD

为XML编码RTFD,xml,cocoa,rtf,nsattributedstring,Xml,Cocoa,Rtf,Nsattributedstring,我需要在XML文件中嵌入RTFD字符串(通常很短) XMLWriter writer(...) NSAttributedString *ns=..... NSRange all=NSMakeRange(0,[s length]); NSData *rtfd=[s RTFDFromRange:all documentAttributes:nil]; writer.Write(rtfd); RTFD不能保证(据我所知——我似乎找不到标准的文档)数据字节即使作为CDATA数据也是安全的——或者确

我需要在XML文件中嵌入RTFD字符串(通常很短)

XMLWriter writer(...)

NSAttributedString *ns=.....
NSRange all=NSMakeRange(0,[s length]);
NSData *rtfd=[s RTFDFromRange:all documentAttributes:nil];

writer.Write(rtfd);
RTFD不能保证(据我所知——我似乎找不到标准的文档)数据字节即使作为CDATA数据也是安全的——或者确实可以表示为UTF8。我应该如何编码它们

目标包括:

  • 人类可读性
  • 紧凑性
  • 编解码速度
尽管很明显,妥协是必要的。

更新: 这实际上只适用于RTF,而不是RTFD。也就是说,如果
[ns containsAttachments]
,它很可能无法在末尾创建
rtfString


您可以在创建RTFD时指定一些选项,使其采用UTF8编码

这段代码对我们来说运行良好(尽管我们使用的是属性列表序列化):


然后,
writer.Write(rtfString)

似乎没有很好的答案

属性列表序列化程序使用的NSData的
description
方法写入十六进制转储。这是可靠和XML安全的,但不紧凑或易读

我目前使用的是Base64编码,它不紧凑(但比十六进制更好),不易读,但对于XML来说也非常安全


ISTM认为UTF8应该很容易地使用Base256-37=Base219编码,在这种编码中我们省略了控制字符00-31以及XML中的特殊字符(<>“&)。我是否遗漏了一些内容,或者这是一个好名字?

除非我弄错了,否则initWithData:在转换为Unicode之前指定数据的编码方式。因此,如果图像附件的字节序列对UTF8是非法的,则这将不起作用。
NSCharacterEncodingDocumentAttribute
设置为e> NSUTF8StringEncoding
创建数据时,数据以UTF8编码。也就是说,在创建数据期间,任何此类字节序列都会变平。我认为这不会起作用:NSCharacterEncodingDocumentAttribute描述正在读取的文档的编码:使用initWithData:options:documentAttributes:error:、initWithHTML:options:documentAttributes:、initWithURL:options:documentAttributes:error:、或readFrom…导入文档时可以识别这些选项键。。。方法(如readFromData:options:DocumentAttribute:)由NSMutableAttributedString实现;已创建rtfdData,但NSString转换失败。(我认为您应该在检查错误之前检查rtfString是否为nil,顺便说一句,因为错误在成功时未定义。)对于
dataFromRange
,提供的属性字典指定了所需的格式。同样的键也用于导入文档,但在这种情况下,将生成文档。我很想看到失败的测试用例,因为这段代码或多或少是从一个运输产品复制的。
NSAttributedString *ns = ...;
NSError *error = nil;
NSString *rtfString = nil;
NSData *rtfdData = [ns dataFromRange:NSMakeRange(0, [ns length])
                   documentAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                       NSRTFDTextDocumentType, NSDocumentTypeDocumentOption,
                                       [NSNumber numberWithInt:NSUTF8StringEncoding], NSCharacterEncodingDocumentAttribute,
                                           nil]
                                error:&error];
if (error == nil) {
    rtfString = [[[NSString alloc] initWithData: rtfdData encoding:NSUTF8StringEncoding] autorelease];
}