想知道是否有一种简单的方法可以在Objective C中执行简单的HTML转义/转义。我想要的是这样的伪代码:
NSString *string = @"<span>Foo</span>"; [string stringByUnescapingHTML];
哪个返回
<span>Foo</span>
希望也转义所有其他HTML实体,甚至ASCII码(例如Ӓ等)。
Cocoa Touch / UIKit中有什么方法可以做到这一点?
包含以下解决方案。可可CF具有CFXMLCreateStringByUnescapingEntities函数,但在iPhone上不可用。
@interface MREntitiesConverter : NSObject <NSXMLParserDelegate>{ NSMutableString* resultString; } @property (nonatomic, retain) NSMutableString* resultString; - (NSString*)convertEntitiesInString:(NSString*)s; @end @implementation MREntitiesConverter @synthesize resultString; - (id)init { if([super init]) { resultString = [[NSMutableString alloc] init]; } return self; } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)s { [self.resultString appendString:s]; } - (NSString*)convertEntitiesInString:(NSString*)s { if (!s) { NSLog(@"ERROR : Parameter string is nil"); } NSString* xmlStr = [NSString stringWithFormat:@"<d>%@</d>", s]; NSData *data = [xmlStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSXMLParser* xmlParse = [[[NSXMLParser alloc] initWithData:data] autorelease]; [xmlParse setDelegate:self]; [xmlParse parse]; return [NSString stringWithFormat:@"%@",resultString]; } - (void)dealloc { [resultString release]; [super dealloc]; } @end