Skip navigation.
 
mlEncoding a string for HTML
FROM : David Dunham
DATE : Thu Jul 20 06:25:45 2006

I'm trying to output a string suitable for using in HTML -- no 
troublesome characters like < and >.

For some reason there's no stringByAddingHTMLEntities, so I came up with

NSArray*        excluded = [NSArray arrayWithObjects: @"doctype", @"html", 
@"head", @"body", @"xml", @"font", @"span", @"p", nil];
NSDictionary*    attr = [NSDictionary dictionaryWithObjectsAndKeys:
       NSHTMLTextDocumentType, NSDocumentTypeDocumentAttribute,
       aTitle, NSTitleDocumentAttribute,
       excluded, NSExcludedElementsDocumentAttribute,
       [NSNumber numberWithInt: NSASCIIStringEncoding], 
NSCharacterEncodingDocumentAttribute,
       nil];

NSAttributedString*    as = [[NSAttributedString alloc] initWithString: 
tString];
NSData*        tData = [as dataFromRange: NSMakeRange(0, [tString length]) 
documentAttributes: attr error: nil];

which almost works. However, a quote " is not converted to &quot; 
like I'd expect. Is there an element I missed here, or do I just have 
to my own pass on the string? (OK, it's probably a single 
replaceOccurrencesOfString:withString:options:range: message, but...)

David Dunham    A Sharp, LLC
Voice/Fax: 206 783 7404    http://a-sharp.com
Efficiency is intelligent laziness.

Related mailsAuthorDate
mlEncoding a string for HTML David Dunham Jul 20, 06:25
mlRe: Encoding a string for HTML Douglas Davidson Jul 20, 18:36
mlRe: Encoding a string for HTML David Dunham Jul 20, 19:18
mlRe: Encoding a string for HTML Douglas Davidson Jul 20, 20:12
mlRe: Encoding a string for HTML Peter Bierman Jul 20, 20:41
mlRe: Encoding a string for HTML Norman Gray Jul 21, 00:13
mlRe: Encoding a string for HTML David Dunham Jul 21, 00:26
mlRe: Encoding a string for HTML Norman Gray Jul 21, 11:40