你举的方法,从磁盘读取一个文件具有给定字符编码(例如UTF-8或ASCII)。它与URL或HTML转义无关。
如果你想添加URL百分号转义,想要此方法:
[myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
请务必阅读有关该方法的文档,因为有什么泄漏出来并独自留下什么一定的微妙之处。在某些情况下,您可能不得不使用更复杂但更灵活的CFURLCreateStringByAddingPercentEscapes()
。 (如果你这样做,请注意,你可以投CFStringRef
到NSString *
,反之亦然。)
没有什么内置的,我知道做XML/HTML风格的实体转义,不过这个功能应该处理的基础知识:
NSString * convertToXMLEntities(NSString * myString) {
NSMutableString * temp = [myString mutableCopy];
[temp replaceOccurrencesOfString:@"&"
withString:@"&"
options:0
range:NSMakeRange(0, [temp length])];
[temp replaceOccurrencesOfString:@"<"
withString:@"<"
options:0
range:NSMakeRange(0, [temp length])];
[temp replaceOccurrencesOfString:@">"
withString:@">"
options:0
range:NSMakeRange(0, [temp length])];
[temp replaceOccurrencesOfString:@"\""
withString:@"""
options:0
range:NSMakeRange(0, [temp length])];
[temp replaceOccurrencesOfString:@"'"
withString:@"'"
options:0
range:NSMakeRange(0, [temp length])];
return [temp autorelease];
}
阅读其他答案的方法来引用字符串作为XML(即,实体替换和<<) – 2012-03-19 09:31:29