using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.IO.Compression; namespace HuaTong.General.Utility
{
/// <summary>
/// html内容处理
/// </summary>
public static class HtmlHelper
{
/// <summary>
/// 纯文本转HTML
/// </summary>
public static string TextToHTML(string value)
{
return TextToHTML(value, false, false);
}
/// <summary>
/// 纯文本转HTML
/// </summary>
public static string TextToHTML(string value, bool isHasEmptyRow)
{
return TextToHTML(value, isHasEmptyRow, false);
}
/// <summary>
/// 纯文本转HTML
/// </summary>
public static string TextToHTML(string value, bool isHasEmptyRow, bool isOutBr)
{
StringBuilder sr = new StringBuilder();
if (isHasEmptyRow)
{
sr.Append(StringHelper.RemoveEmptyRow(value));
}
else
{
sr.Append(value);
} sr.Replace("&", "&amp;");
sr.Replace(">", "&gt;");
sr.Replace("<", "&lt;");
sr.Replace(" ", "&nbsp;");
sr.Replace("\"", "&quot;");
sr.Replace("©", "&copy;");
sr.Replace("®", "&reg;");
sr.Replace("×", "&times;");
sr.Replace("÷", "&divide;");
if (isOutBr)
{
sr.Replace("\r\n", "<br>");
sr.Replace("\r", "<br>");
sr.Replace("\n", "<br>");
}
else
{
sr.Insert(, "<p>");
sr.Replace("\r\n", "\r");
sr.Replace("\r", "</p>\r\n<p>");
sr.Append("</p>");
} return sr.ToString();
} /// <summary>
/// HTML输出为JS
/// </summary>
public static string HtmlToScript(string value)
{
StringBuilder sr = new StringBuilder();
sr.Append(value);
sr.Replace("\\", "\\\\");
sr.Replace("/", "\\/");
sr.Replace("'", "\\'");
sr.Replace("\"", "\\\"");
string[] strs = sr.ToString().Split(new char[] { '\r', '\n' },
StringSplitOptions.RemoveEmptyEntries); return String.Format("document.writeln(\"{0}\");",
String.Join("\");\r\ndocument.writeln(\"", strs),
StringSplitOptions.RemoveEmptyEntries);
} /// <summary>
/// JS脚本输出字符串
/// </summary> /// <returns></returns>
public static string ScriptStringFormat(string value)
{
value = value.Replace("\\", "\\\\");
value = value.Replace("'", "\\'");
value = value.Replace("\"", "\\\"");
return value;
} /// <summary>
/// HTML转纯文本
/// </summary>
public static string HtmlToText(string value)
{
string regexstr = @"(&(#)?.+;)|(<[^>]*>)";
return Regex.Replace(value, regexstr, "", RegexOptions.IgnoreCase);
} /// <summary>
/// 过滤HTML中的不安全标签
/// </summary>
public static string HtmlFilter(string value)
{
value = Regex.Replace(value, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
value = Regex.Replace(value, @"(select|textarea|input|link|iframe|frameset|frame|form|applet|embedlayer|ilayer|meta|object|script|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
value = Regex.Replace(value, @"javascript|eval", "", RegexOptions.IgnoreCase);
return value;
} /// <summary>
/// 获取源代码
/// </summary>
public static string GetHtmlContent(string url, string encoding)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
StreamReader reader = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = ;
request.AllowAutoRedirect = false;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
if (response.ContentEncoding != null && StringHelper.IsEqualString(response.ContentEncoding,"gzip"))
reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), Encoding.GetEncoding(encoding));
else
reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string html = reader.ReadToEnd();
return html;
}
}
catch
{
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
if (reader != null)
reader.Close();
if (request != null)
request = null;
}
return string.Empty;
}
/// <summary>
/// 获取HTML网页的编码
/// </summary> /// <returns></returns>
public static string GetEncoding(string url)
{
string charset = string.Empty;
HttpWebRequest request = null;
HttpWebResponse response = null;
StreamReader reader = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = ;
request.AllowAutoRedirect = false;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < * )
{
if (response.ContentEncoding != null && StringHelper.IsEqualString(response.ContentEncoding, "gzip"))
reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
else
reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
string html = reader.ReadToEnd();
Regex reg_charset = new Regex(@"charset\b\s*=\s*(?<charset>[^""]*)");
if (reg_charset.IsMatch(html))
{
return reg_charset.Match(html).Groups["charset"].Value;
}
else if (response.CharacterSet != string.Empty)
{
return response.CharacterSet;
}
else
return Encoding.Default.BodyName;
}
}
catch
{
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
if (reader != null)
reader.Close();
if (request != null)
request = null;
}
return Encoding.Default.BodyName;
}
}
}

c# html内容处理类的更多相关文章

  1. js进阶 10-10 可见伪类选择器和内容伪类选择器的作用

    js进阶 10-10  可见伪类选择器和内容伪类选择器的作用 一.总结 一句话总结:分组来描述.内容伪类选择器就是  四个  包含.可见的伪类选择器就是可见和不可见.查找功能,也就是内容伪类选择器非常 ...

  2. 前端(六)—— 伪类选择器:a标签的伪类、内容伪类、索引伪类、取反伪类

    a标签的伪类.内容伪类.索引伪类.取反伪类 一.a标签的四大伪类 :link:未访问状态 :hover:悬浮状态 :active:活跃状态 :visited:已访问状态 四大伪类也可用于其他标签 &l ...

  3. poi读取excel内容工具类

    该工具类可以读取excel2007,excel2003等格式的文件,xls.xlsx文件格式 package com.visolink; import org.apache.poi.hssf.user ...

  4. [android开发之内容更新类APP]三、项目的基本功能之布局

    应用宝的下载地址:http://android.myapp.com/myapp/detail.htm?apkName=com.jov.laughter 其它的市场如木蚂蚁,安卓市场.搜狐也都有了 注: ...

  5. org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException 前言中不允许有内容 来自类路径资源的XML文档中的第1行是无效的

    今天复习一下Spring和Hibernate的整合,遇到了一个问题,报错信息如下: org.springframework.beans.factory.xml.XmlBeanDefinitionSto ...

  6. java总结第二次(剩余内容)//类和对象1

    7.成员变量和局部变量 成员变量:在类中定义,用来描述对象将要有什么 局部变量:在类的方法中定义,在方法中保存临时数据 区别:作用域不同 局部变量的作用域仅限于定义它的方法 成员变量的作用域在整个类内 ...

  7. java 记录对象前后修改的内容(工具类)

    有时候业务需要,需记录一条记录的修改历史,但是不能为完成任务而硬编码,不靠谱 这种情况可以使用java反射来完成 对对象属性的描述可以通过自定义注解来完成,读取里面的属性进而记录修改历史. 在对象的属 ...

  8. [android开发之内容更新类APP]二、这几日的结果

    android教程即将開始 话说这开了blog之后,就一直在试用自己的app,发现.TM的真的非常不爽,不好用,好吧.本来打算放弃了.只是看到手机里还有还有一个坑,干脆又一次做一个吧. 原来的神回复A ...

  9. [转]java按指定编码写入和读取文件内容的类

    读文件: BufferedReader 从字符输入流中读取文本,缓冲各个字符,从而提供字符.数组和行的高效读取. 可以指定缓冲区的大小,或者可使用默认的大小.大多数情况下,默认值就足够大了. 通常,R ...

随机推荐

  1. GRUB2 分析 (四)

    接上一篇 kernel.img由startup.S以及一堆c文件编译而成.这是一个ELF格式的文件.(其实前面的boot.img. diskboot.img.lzma_decompress.img本来 ...

  2. DevOps实践之持续集成Jenkins(最新版本测试)

    一.安装Jenkins (1)下载并安装配置Java Development Kit 8 [root@localhost ~]# rpm -ivh jdk-8u161-linux-x64.rpm Pr ...

  3. LaTeX模板 - FORMCM

    LaTex 模板 - FORMCM \documentclass{mcmthesis} \mcmsetup{CTeX = true, % 使用 CTeX 套装时,设置为 true tcn = 8989 ...

  4. 解题报告:hdu1008 Elvator

    2017-09-07 19:30:22 writer:pprp 比较顺利,最近生活出现了各种问题, 发生了很多矛盾,我要耐下心来,最重要的不是努力不努力,而是选择 希望我能处理好人际关系还有学业上的压 ...

  5. 调试bug的几种方法

    1.php中的dump,echo,exit 2.浏览器的f12 3.安装xdebug扩展(debugger调试器,profiler探查器,trace代码跟踪) profile日志能记录函数的执行耗时和 ...

  6. phpstorm 右下角显示updating indices,一直有任务卡着

    其实就是生成的这个node_modules目录内文件太多了,选中node_modules这个目录右键,选择Excluded 一直在加载忽略掉这个文件就可以了

  7. MooseFS技术详解

    原文 http://www.tuicool.com/articles/vQvEZ3y MooseFS是一款具有冗余容错功能的分布式文件系统.它把数据分散在多台服务器上,确保一份数据多个备份副本,对外提 ...

  8. Dubbo 和 Spring Cloud微服务架构 比较及相关差异

    你真的了解微服务架构吗?听听八年阿里架构师怎样讲述Dubbo和Spring Cloud微服务架构. 微服务架构是互联网很热门的话题,是互联网技术发展的必然结果.它提倡将单一应用程序划分成一组小的服务, ...

  9. WebBrowser提交submit后界面不刷新的解决办法

    一个Form里有一个WebBrowser和一个Button,在Button_Click里执行 htmlDocument=WebBrowser.Document得到当前document 当htmlDoc ...

  10. 项目使用文档管理:MediaWiki安装及使用入门

    MediaWiki是著名的开源wiki引擎,全球最大的wiki项目维基百科(百科词条协作系统)是使用MediaWiki的成功范例,MediaWiki的最大作用在于对知识的归档,可用于构建企业/个人知识 ...