Encode NSString for XML/HTML

后端 未结 14 1355
误落风尘
误落风尘 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:

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

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

    [[[[[myStr stringByReplacingOccurrencesOfString: @"&" withString: @"&"]
     stringByReplacingOccurrencesOfString: @"\"" withString: @"""]
     stringByReplacingOccurrencesOfString: @"'" withString: @"'"]
     stringByReplacingOccurrencesOfString: @">" withString: @">"]
     stringByReplacingOccurrencesOfString: @"<" withString: @"<"];
    

提交回复
热议问题