开发者

How to convert NSString HTML markup to plain text NSString?

Been searching the net for an example of how to convert HTML string markup into Plain text.

I get my information 开发者_JAVA技巧from a feed which contains HTML, I then display this information in a Text View. does the UITextView have a property to convert HTML or do I have to do it in code. I tried:

NSString *str = [NSString stringWithCString:self.fullText encoding:NSUTF8StringEndcoding];

but doesn't seem to work. Anyone got any ideas?


You can do it by parsing the html by using NSScanner class

- (NSString *)flattenHTML:(NSString *)html {

    NSScanner *theScanner;
    NSString *text = nil;
    theScanner = [NSScanner scannerWithString:html];

    while ([theScanner isAtEnd] == NO) {

        [theScanner scanUpToString:@"<" intoString:NULL] ; 

        [theScanner scanUpToString:@">" intoString:&text] ;

        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
    }
    //
    html = [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    return html;
}

Hope this helps.


If you are using UIWebView then it will be easier to parse HTML to text:

fullArticle = [webView stringByEvaluatingJavaScriptFromString:@"document.body.getElementsByTagName('article')[0].innerText;"]; // extract the contents by tag

fullArticle = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerText"]; // extract text inside body part of HTML


you can't do it directly i guess.. however you can use NSXML Parser and parse the HTML and retrieve exactly what you want...


If you need to present the text in read-only fashion, why not use UIWebView?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜