c# html内容处理类
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("&", "&");
sr.Replace(">", ">");
sr.Replace("<", "<");
sr.Replace(" ", " ");
sr.Replace("\"", """);
sr.Replace("©", "©");
sr.Replace("®", "®");
sr.Replace("×", "×");
sr.Replace("÷", "÷");
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内容处理类的更多相关文章
- js进阶 10-10 可见伪类选择器和内容伪类选择器的作用
js进阶 10-10 可见伪类选择器和内容伪类选择器的作用 一.总结 一句话总结:分组来描述.内容伪类选择器就是 四个 包含.可见的伪类选择器就是可见和不可见.查找功能,也就是内容伪类选择器非常 ...
- 前端(六)—— 伪类选择器:a标签的伪类、内容伪类、索引伪类、取反伪类
a标签的伪类.内容伪类.索引伪类.取反伪类 一.a标签的四大伪类 :link:未访问状态 :hover:悬浮状态 :active:活跃状态 :visited:已访问状态 四大伪类也可用于其他标签 &l ...
- poi读取excel内容工具类
该工具类可以读取excel2007,excel2003等格式的文件,xls.xlsx文件格式 package com.visolink; import org.apache.poi.hssf.user ...
- [android开发之内容更新类APP]三、项目的基本功能之布局
应用宝的下载地址:http://android.myapp.com/myapp/detail.htm?apkName=com.jov.laughter 其它的市场如木蚂蚁,安卓市场.搜狐也都有了 注: ...
- org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException 前言中不允许有内容 来自类路径资源的XML文档中的第1行是无效的
今天复习一下Spring和Hibernate的整合,遇到了一个问题,报错信息如下: org.springframework.beans.factory.xml.XmlBeanDefinitionSto ...
- java总结第二次(剩余内容)//类和对象1
7.成员变量和局部变量 成员变量:在类中定义,用来描述对象将要有什么 局部变量:在类的方法中定义,在方法中保存临时数据 区别:作用域不同 局部变量的作用域仅限于定义它的方法 成员变量的作用域在整个类内 ...
- java 记录对象前后修改的内容(工具类)
有时候业务需要,需记录一条记录的修改历史,但是不能为完成任务而硬编码,不靠谱 这种情况可以使用java反射来完成 对对象属性的描述可以通过自定义注解来完成,读取里面的属性进而记录修改历史. 在对象的属 ...
- [android开发之内容更新类APP]二、这几日的结果
android教程即将開始 话说这开了blog之后,就一直在试用自己的app,发现.TM的真的非常不爽,不好用,好吧.本来打算放弃了.只是看到手机里还有还有一个坑,干脆又一次做一个吧. 原来的神回复A ...
- [转]java按指定编码写入和读取文件内容的类
读文件: BufferedReader 从字符输入流中读取文本,缓冲各个字符,从而提供字符.数组和行的高效读取. 可以指定缓冲区的大小,或者可使用默认的大小.大多数情况下,默认值就足够大了. 通常,R ...
随机推荐
- jQuery中this 和 $(this)
var node = $('#id'); node.click(function(){ this.css('display','block'); //报错 this是一个html元素,不是jquer ...
- P(Y|X) 和 P(X,Y)
P ( x | y ):在Y发生的条件下,X发生的概率.P ( x , y )P(x,y)说明该事件与两个因素有关,比如设是因素A,B.P(x,y)=P{因素A处于x状态,因素B处于y状态}确切地说P ...
- http://www.jb51.net/article/28619.htm
http://www.jb51.net/article/28619.htm js autocomplete 自动完成
- 记jsp判断
empty:表示空字符串,null,空数组,空集合. ! empty:表示非空字符串,非null,非空数组,非空集合.
- Putting Apache Kafka To Use: A Practical Guide to Building a Stream Data Platform-part 1
转自: http://www.confluent.io/blog/stream-data-platform-1/ These days you hear a lot about "strea ...
- ASP.NET.Identity 加密算法
public static string HashPassword(string password) { if (password == null) { throw new ArgumentNullE ...
- Python学习札记(二十一) 函数式编程2 map/reduce
参考:map/reduce Note 1.map():map()函数接收两个参数,一个是函数,一个是Iterable.map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回. ...
- poj 2255 Tree Recovery 分治
Tree Recovery Description Little Valentine liked playing with binary trees very much. Her favorite g ...
- RabbitMQ 的路由模式 Topic模式
模型 生产者 package cn.wh; import java.io.IOException; import java.util.concurrent.TimeoutException; impo ...
- ubuntu install vue , vue-cli , how to create project..
<<install node.js <<the n model is manage the node.js version npm install -g n n stable ...