iOS 轻量级 HTML 解析方案

一个轻量级的 Objective-C-HMTL-Parser 解析库,这里主要是希望 HTML 解析出想要的标签字段。

题外:如果是要将 HTML 解析成富文本展示,推荐 DTCoreText

添加到 framework 或 app 在 Build Setting 的 Header Search Paths 添加 $(SDKROOT)/usr/include/libxml2。

如果是添加到 podspec 则添加,则:

s.library = 'xml2'
s.xcconfig = { 'HEADER_SEARCH_PATHS' => '$(SDKROOT)/usr/include/libxml2', 'OTHER_LDFLAGS' => '-lxml2' }

解决 libxml2 中文乱码

/**
 解决 xml2 中文乱码
 参考:https://blog.fedepot.com/ios-9-htmlparserzhong-wen-luan-ma-wen-ti/
 */
-(id)initWithString:(NSString*)string error:(NSError**)error
{
    if (self = [super init])
    {
        _doc = NULL;
        
        if ([string length] > 0)
        {
            CFStringEncoding cfenc = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
            CFStringRef cfencstr = CFStringConvertEncodingToIANACharSetName(cfenc);
            const char *enc = CFStringGetCStringPtr(cfencstr, 0);
            //Fix iOS9 Chinese wrong characters - begin
            char buffer[255];
            if (enc == NULL) {
                if (CFStringGetCString(cfencstr, buffer, 255, kCFStringEncodingUTF8)) enc = buffer;
            }
            //Fix iOS9 Chinese wrong characters - end
            // _doc = htmlParseDoc((xmlChar*)[string UTF8String], enc);
            int optionsHtml = HTML_PARSE_RECOVER;
            optionsHtml = optionsHtml | HTML_PARSE_NOERROR; //Uncomment this to see HTML errors
            optionsHtml = optionsHtml | HTML_PARSE_NOWARNING;
            _doc = htmlReadDoc ((xmlChar*)[string UTF8String], NULL, enc, optionsHtml);
        }
        else
        {
            if (error) {
                *error = [NSError errorWithDomain:@"HTMLParserdomain" code:1 userInfo:nil];
            }
        }
    }
    
    return self;
}

推荐阅读更多精彩内容