从字符串中删除HTML标签

41
如何从以下字符串中删除HTML标签?
<P style="MARGIN: 0cm 0cm 10pt" class=MsoNormal><SPAN style="LINE-HEIGHT: 115%; 
FONT-FAMILY: 'Verdana','sans-serif'; COLOR: #333333; FONT-SIZE: 9pt">In an 
email sent just three days before the Deepwater Horizon exploded, the onshore 
<SPAN style="mso-bidi-font-weight: bold"><b>BP</b></SPAN> manager in charge of 
the drilling rig warned his supervisor that last-minute procedural changes were 
creating "chaos". April emails were given to government investigators by <SPAN 
style="mso-bidi-font-weight: bold"><b>BP</b></SPAN> and reviewed by The Wall 
Street Journal and are the most direct evidence yet that workers on the rig 
were unhappy with the numerous changes, and had voiced their concerns to <SPAN 
style="mso-bidi-font-weight: bold"><b>BP</b></SPAN>’s operations managers in 
Houston. This raises further questions about whether <SPAN 
style="mso-bidi-font-weight: bold"><b>BP</b></SPAN> managers properly 
considered the consequences of changes they ordered on the rig, an issue 
investigators say contributed to the disaster.</SPAN></p><br/>  

我正在将HTML内容写入Aspose.PDF中,但是PDF中会显示HTML标签。如何去除这些标签?


1
我尝试了HTMLDecode,但没有起作用。 - jvm
你需要进行HTML编码以转义标签。 - Joe
1
你想去掉标签还是应用格式? - SLaks
2
http://www.dotnetperls.com/remove-html-tags - onder
2个回答

106

警告:这种方法并不适用于所有情况,并且不应该用于处理不受信任的用户输入。

using System.Text.RegularExpressions;
...
const string HTML_TAG_PATTERN = "<.*?>";

static string StripHTML (string inputString)
{
   return Regex.Replace 
     (inputString, HTML_TAG_PATTERN, string.Empty);
}

14
不应该使用正则表达式来解析类似HTML这样的上下文无关语法。如果HTML由外部实体提供,那么它可以轻松地被操纵以逃避您的正则表达式。 - Mark E. Haase
10
公共的靜態字符串StripTagsCharArray(string source) { 長度為source.Length的字符數組 = 新字符[source.Length]; 數組索引= 0; 布爾變量 inside = false; for (int i = 0; i < source.Length; i++) { 字符let = source[i]; 如果(let == '<') { inside = true; 继续; } 如果(let == '>') { inside = false; 继续; } 如果(!inside) { 数组[数组索引] = let; 数组索引++; } } 返回新字符數組的字符串(數組, 0, 数组索引); }它比正則快了8倍。 - AuthorProxy
8
另外,人们会从在SO上看到的例子中推断。最终会有人阅读此内容并尝试重写它,只是为了删除<script>标签,他们不会意识到这对于预防XSS特别不适合(因为可以很容易地被欺骗)。在SO上,我认为解决方案应该针对广泛的受众编写,而不仅仅是向问问题的单个人编写。(否则,为什么要首先公开发布问题和答案呢?) - Mark E. Haase
7
如果你想要有效的HTML5,那么<p data-foo=">">Bar</script>怎么样?但是请记住,有些人使用你的代码来处理未知来源的HTML,而且HTML不能保证有效!如果你在答案前加上“警告:这并不适用于所有情况,并且不应该用于处理不可信任的用户输入。”我会支持你的答案。我怀疑你有58个赞成票,是因为58个人(无论生死)在地球上不知道或不介意你的解决方案在某些测试用例中是错误的。 - Mark E. Haase
3
好的,我已经做了修改,谢谢。 - capdragon
显示剩余6条评论

10

你应该使用HTML Agility Pack

HtmlDocument doc = ...
string text = doc.DocumentElement.InnerText;

36
我不明白为什么有些人会建议使用敏捷包(Agility Pack),因为body的.InnerText属性(举例)并不能呈现无标记字符串。在stackoverflow上,有很多人下载了敏捷包却发现仍然看到标记和脚本标签,这很令人困惑。 - Eric
1
对我来说似乎很有效。肯定比上面的任何解决方案都更优雅。 - Nate Zaugg
1
这个解决方案只是去除包装的HTML标签,不能保证所有标记都被删除。 - tif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接