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. web.xml listener配置

    listener简介: <listener>能为web应用创建监视器,监听上下文的各种事件,如:application和session事件,这些监视器都是按相同的方式定义,它的功能取决于各 ...

  2. HBase安装过程

    1).上传,解压,重命名,修改环境变量/etc/profile 2).修改 hbase-env.sh 文件 export JAVA_HOME=/usr/java/jdk1.7.0_27 //Java ...

  3. bat(续七)-for语句(循环结构)

    for语句(循环结构) for语句可以实现类似于C语言里面的循环结构,当然for语句的功能要更强大一点,通过不同的开关可以实现更多的功能.for语句有多个开关,不同开关将会实现不同的功能.   1.无 ...

  4. JAVA基础补漏--SET

    HashSet: 1.无序集合. 2.底层是一个哈希表结构,查询速速很快. 哈希表==数据 + 链表/红黑树 特点:查询速度快. 存储数据到SET中: 1.计算数据的HASH值. 2.查看有没有相同H ...

  5. mysql5.7.22安装步骤

    在官网上下载mysql的压缩包,然后解压 (下载地址:https://dev.mysql.com/downloads/mysql/) 1.打开cmd,建议使用管理员的身份打开cmd,如果不用使用管理员 ...

  6. NOIP2015 T4 推销员 贪心+堆优化

    前几天在学堆,这个数据结构貌似挺简单的,但是我看了很久啊QAQ... 今天算是搞懂了吧...于是想到了这道题...(当初悄悄咪咪看题解记得一点) 点我看题 放洛谷的题... 题意的话,大概就是有n个房 ...

  7. LeetCode——Unique Paths

    Question A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram be ...

  8. Sublime Text指南

    转自: http://lucida.me/blog/sublime-text-complete-guide/  摘要(Abstract) 本文系统全面的介绍了Sublime Text,旨在成为最优秀的 ...

  9. 第八篇:Spark SQL Catalyst源码分析之UDF

    /** Spark SQL源码分析系列文章*/ 在SQL的世界里,除了官方提供的常用的处理函数之外,一般都会提供可扩展的对外自定义函数接口,这已经成为一种事实的标准. 在前面Spark SQL源码分析 ...

  10. C# 往string [] arr 数组插入元素

    string [] arr ; List<string> _list = new List<string>(arr ); for(int i ;i<10;i++) { _ ...