情景:
TextView加載后端接口獲取到的html富文本
遇到的問題:
客戶端通過接口取到的數據如下:
<p style="margin-top: 0px; margin-bottom: 0px; padding: 0px;
用 TextView 的 Html.fromHtml 解析后很多標簽都無法解析,以文案的形式顯示出來了
問題分析及解決:
1、因html保存數據時為了避免XSS攻擊,將html數據進行了轉義,所以獲取的數據不是以<> 這種html的格式出現,
轉義規則參考: http://tool.oschina.net/commons?type=2,
轉義后的
2、TextView加載時,先用 Html.fromHtml 進行轉化為正常的html標簽,
<p style="margin-top: 0px; margin-bottom: 0px; padding: 0px; color: rgb(51, 51, 51);
但因為TextView支持的標簽很少,導致顯示有問題
3、用正則表達式過濾掉所有標簽,只保留換行標簽,如下:
private String getHTMLStr(String htmlStr){ //先將換行符保留,然后過濾標簽 Pattern p_enter = Pattern.compile("<br/>", Pattern.CASE_INSENSITIVE); Matcher m_enter = p_enter.matcher(htmlStr); htmlStr = m_enter.replaceAll("\n"); //過濾html標簽 Pattern p_html = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE); Matcher m_html = p_html.matcher(htmlStr); return m_html.replaceAll(""); }