Encode NSString for XML/HTML

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

    the samets's routine forgot the hex digit. Here's the routine I came up with that works:

    - (NSString*)convertEntities:(NSString*)string
    {
    
    NSString    *returnStr = nil;
    
        if( string )
        {
            returnStr = [ string stringByReplacingOccurrencesOfString:@"&" withString: @"&"  ];
    
            returnStr = [ returnStr stringByReplacingOccurrencesOfString:@""" withString:@"\""  ];
    
            returnStr = [ returnStr stringByReplacingOccurrencesOfString:@"'" withString:@"'"  ];
    
            returnStr = [ returnStr stringByReplacingOccurrencesOfString:@"9" withString:@"'"  ];
    
            returnStr = [ returnStr stringByReplacingOccurrencesOfString:@"’" withString:@"'"  ];
    
            returnStr = [ returnStr stringByReplacingOccurrencesOfString:@"–" withString:@"'"  ];
    
            returnStr = [ returnStr stringByReplacingOccurrencesOfString:@">" withString:@">"  ];
    
            returnStr = [ returnStr stringByReplacingOccurrencesOfString:@"<" withString:@"<"  ];
    
            returnStr = [ [ NSString alloc ] initWithString:returnStr ];
        }
    
        return returnStr;
    }
    

提交回复
热议问题