본문 바로가기
프로그래밍 속 지혜/C#

C# HTML Escape 문자 처리 - HTML Encode & Decode

by 생속지 2021. 1. 23.
반응형
HttpUtility.HtmlEncode(">");

HTML 의 Escape 문자를 처리하는 방법입니다.

예를 들면 "<" 문자는 "&lt;"이고 ">" 문자는 "&gt;"인데 이러한 처리 하는 방법입니다.

그리고 반대로 처리 하는 방법도 알아볼께요.

 

1. HTML Escape 문자를 처리하는 클래스는 HttpUtility인데 네임스페이스는 System.Web으로 참조에 추가하세요.

 

2. HTML Encode 하기 ("<" → "&lt;")

string encodeStr = HttpUtility.HtmlEncode(">")

 

3. HTML Decode 하기("&lt;" → "<")

string decodedStr = HttpUtility.HtmlDecode("&lt;");

 

4. 예제

using System.Web;

...

string str = "&, <, >, \" ";
Debug.WriteLine("Original String : " + str);

// Encode the string.
string encodedStr = HttpUtility.HtmlEncode(str);
Debug.WriteLine("Encode String : " + encodedStr);

// Decode the encoded string.
string decodedStr = HttpUtility.HtmlDecode(encodedStr);
Debug.WriteLine("Decode String : " + decodedStr);

 

5. 결과

Original String : &, <, >, " 
Encode String : &amp;, &lt;, &gt;, &quot; 
Decode String : &, <, >, " 

 

※ 저는 크롤링을 할 때 해당 클래스를 이용하여 HTML을 Encode 또는 Decode 활용하고 있습니다.

반응형

댓글