如何将 NSString HTML 标记转换为纯文本 NSString?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2606134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert NSString HTML markup to plain text NSString?
提问by Frames84
Been searching the net for an example of how to convert HTML string markup into Plain text.
一直在网上搜索如何将 HTML 字符串标记转换为纯文本的示例。
I get my information 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:
我从包含 的提要中获取信息HTML
,然后在文本视图中显示此信息。是否UITextView
有要转换的属性,HTML
或者我必须在代码中进行转换。我试过:
NSString *str = [NSString stringWithCString:self.fullText encoding:NSUTF8StringEndcoding];
but doesn't seem to work. Anyone got any ideas?
但似乎不起作用。有人有任何想法吗?
回答by Madhup Singh Yadav
You can do it by parsing the html by using NSScanner class
您可以通过使用 NSScanner 类解析 html 来完成
- (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.
希望这可以帮助。
回答by Veera Raj
If you are using UIWebView then it will be easier to parse HTML to text:
如果您使用 UIWebView,那么将 HTML 解析为文本会更容易:
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
回答by Mihir Mehta
you can't do it directly i guess.. however you can use NSXML Parser and parse the HTML and retrieve exactly what you want...
我猜你不能直接做到这一点......但是你可以使用 NSXML Parser 并解析 HTML 并准确地检索你想要的......
回答by dusker
If you need to present the text in read-only fashion, why not use UIWebView?
如果您需要以只读方式呈现文本,为什么不使用 UIWebView?