Objective C HTML 转义/转义 [英] Objective C HTML escape/unescape

查看:30
本文介绍了Objective C HTML 转义/转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道是否有一种简单的方法可以在 Objective C 中进行简单的 HTML 转义/转义.我想要的是这样的伪代码:

Wondering if there is an easy way to do a simple HTML escape/unescape in Objective C. What I want is something like this psuedo code:

NSString *string = @"<span>Foo</span>";
[string stringByUnescapingHTML];

哪个返回

<span>Foo</span>

希望对所有其他 HTML 实体以及甚至 ASCII 代码(如 Ӓ 等)进行转义.

Hopefully unescaping all other HTML entities as well and even ASCII codes like Ӓ and the like.

Cocoa Touch/UIKit 中是否有任何方法可以做到这一点?

Is there any methods in Cocoa Touch/UIKit to do this?

推荐答案

这个 链接 包含以下解决方案.Cocoa CF 具有 CFXMLCreateStringByUnescapingEntities 函数,但在 iPhone 上不可用.

This link contains the solution below. Cocoa CF has the CFXMLCreateStringByUnescapingEntities function but that's not available on the 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

这篇关于Objective C HTML 转义/转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆