Encode NSString for XML/HTML

后端 未结 14 1212
误落风尘
误落风尘 2020-11-28 04:25

Is there a way to HTML encode a string (NSString) in Objective-C, something along the lines of Server.HtmlEncode in .NET?

相关标签:
14条回答
  • 2020-11-28 05:04

    There isn't an NSString method that does that. You'll have to write your own function that does string replacements. It is sufficient to do the following replacements:

    • '&' => "&"
    • '"' => """
    • '\'' => "'"
    • '>' => ">"
    • '<' => "&lt;"

    Something like this should do (haven't tried):

    [[[[[myStr stringByReplacingOccurrencesOfString: @"&" withString: @"&amp;"]
     stringByReplacingOccurrencesOfString: @"\"" withString: @"&quot;"]
     stringByReplacingOccurrencesOfString: @"'" withString: @"&#39;"]
     stringByReplacingOccurrencesOfString: @">" withString: @"&gt;"]
     stringByReplacingOccurrencesOfString: @"<" withString: @"&lt;"];
    
    0 讨论(0)
  • 2020-11-28 05:04

    Use the message in the example below :

    anyStringConverted = [anyString stringByReplacingOccurrencesOfString:@"\n" withString:@"<br>"]; 
    

    This converts 'new line' command to corresponding html code. But to convert symbols, you have to write the corresponding html number. You can see the complete list of html numbers here at

    http://www.ascii.cl/htmlcodes.htm

    0 讨论(0)
提交回复
热议问题