2011-02-02 9 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 [소스. 길이]; \t int arrayIndex = 0; \t bool inside = false; \t for (int i = 0; i ') 경우에 { \t \t \t 내부 = FALSE; \t \t 계속; \t} \t 경우 \t \t \t { 배열 [arrayIndex =하게 (내부!); \t \t arrayIndex ++; \t} \t} \t return new string (array, 0, arrayIndex); }'Regex보다 약 8 배 빠름 – AuthorProxy

+0

@ mehaase 대부분의 부분에 동의합니다. 하지만 파싱에 관해 누가 말 했나요? 그는 단순히 태그를 제거하려고합니다. 근본적인 구별은 항상 정규 표현식을 사용하는 PARSING html과 정규 표현식을 사용하는 HTML 검색 또는 일치 사이에서 이루어져야합니다. – capdragon

10

당신은 사용해야 HTML Agility Pack :

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

왜 사람들이 대답을 사용하는지 이유를 모르겠다. 민첩성 팩, 신체의 .InnerText (예를 들어) 마크 업없는 문자열을 렌더링하지 않기 때문에. 그래서 Agility Pack을 얻은 사람들이 왜 마크 업 (markup), 스크립트 태그 (script tags)를 아직도 보는지 궁금합니다. – radpin