2011-02-02 12 views
28

次の文字列からHTMLタグを削除するにはどうすればよいですか?文字列の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/> 

私はAsponse.PDFに書きますが、HTMLタグはPDFに表示されています。どうすれば削除できますか?

+0

私はあなたがタグをエスケープするためにHTMLエンコードする必要が – jvm

+0

動作しませんでした、HTMLDecodeを試してみました。 – Joe

+0

タグを削除するか、書式を適用しますか? – SLaks

答えて

89

警告:This does not work for all cases and should not be used to process untrusted user input.

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

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

-1 HTMLのような文脈自由文法を解析するために正規表現を使うべきではありません。 HTMLが何らかの外部エンティティによって提供されている場合、HTMLを簡単に操作して正規表現を回避することができます。 –

+6

'public static string StripTagsCharArray(文字列ソース) { \t char [] array = new char [source.Length]; \t int arrayIndex = 0; \t bool inside = false; (int i = 0; i ')場合 \t {\t \tが内部偽=。 \t \t続き; \t} \t \t { \t \t配列[arrayIndex] =せIF(内部!)。 \t \t arrayIndex ++; \t} \t} \t return new string(array、0、arrayIndex); } 'Regexより約8倍高速です – AuthorProxy

+0

@ mehaaseほとんどの場合私は同意します。しかし、誰が構文解析について何か言った?彼は単にタグを削除したいと思っています。基本的な区別は、正規表現を使用して実際にパーシングしているHTMLと、正規表現を使っていくつかのhtmlを検索するかマッチさせるかの間で常に行わなければなりません。 – capdragon

10

あなたはHTML Agility Packを使用する必要があります。

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

私は本当に人々が(例として)Bodyの.InnerTextは、マークアップのない文字列をレンダリングしないため、Agility Packです。だから、Agility Packを入手して、マークアップやスクリプトタグをなぜ見つめているのか不思議な人がたくさんいます。 – radpin

関連する問題