Encode NSString for XML/HTML

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;"];

Leave a Comment