[C#] HTML &# Character To Plain Text

HttpWebRequest 클래스를 사용하여 HttpWebResponse 데이터를 가져올 때, HTML을 &#과 같은 형태의 문자열로 수신할 수 있습니다. 이때에 해당 캐릭터를 평문으로 변환하려면 HttpUtility 클래스를 사용하는 방법이 있습니다.

HTML &# Character To Plain Text

다음과 같이 WebRequest, WebResponse 예제를 이용하는 경우 HTML innerHtml 값이 원하는 양식이 아닌 &#과 같이 인코딩 된 텍스트가 반환될 때 사용해 보세요.

string resTxt = string.Empty;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
    using (Stream st = res.GetResponseStream())
    {
        using (StreamReader sr = new StreamReader(st))
        {
            resTxt = sr.ReadToEnd();
        }
    }
}

먼저, 참조에서 System.Web을 추가합니다. 그리고 해당 네임스페이스의 HttpUtility 클래스를 활용하여, HtmlDecode 메서드를 사용해 보세요. TextWriter 매개변수를 더하는 것도 가능합니다.

//
// 요약:
//     Converts a string that has been HTML-encoded for HTTP transmission into a decoded
//     string.
//
// 매개 변수:
//   s:
//     The string to decode.
//
// 반환 값:
//     A decoded string.
public static string HtmlDecode(string s);

댓글