IT박스

ASP.NET의 문자열에서 HTML 태그를 어떻게 제거 할 수 있습니까?

itboxs 2020. 7. 12. 10:21
반응형

ASP.NET의 문자열에서 HTML 태그를 어떻게 제거 할 수 있습니까?


ASP.NET을 사용하여 주어진 문자열에서 HTML 태그를 안정적으로 제거하는 방법은 무엇입니까? PHP와 같은 것을 찾고 strip_tags있습니다.

예:

<ul><li>Hello</li></ul>

산출:

"여보세요"

나는 바퀴를 재발 명하지 않으려 고 노력했지만 지금까지 내 요구를 충족시키는 것을 찾지 못했습니다.


문자열에서 모든 HTML 태그를 제거 하는 경우 정규식에서도 안정적으로 작동합니다. 바꾸다:

<[^>]*(>|$)

빈 문자열로 전체적으로. 나중에 문자열을 정규화하는 것을 잊지 마십시오.

[\s\r\n]+

단일 공간으로 결과를 트리밍합니다. 선택적으로 HTML 문자 엔티티를 실제 문자로 대체하십시오.

참고 :

  1. >속성 값에 HTML 및 XML 허용이 제한 됩니다. 이 솔루션 이러한 값이 발생하면 깨진 마크 업 반환합니다.
  2. 솔루션은 다음과 같이 기술적으로 안전합니다. 결과에는 사이트 간 스크립팅을 수행하거나 페이지 레이아웃을 손상시키는 데 사용할 수있는 항목이 포함되지 않습니다. 매우 깨끗하지 않습니다.
  3. HTML 및 정규식과 마찬가지로 모든 상황 에서 올바르게 사용해야하는 경우 적절한 파서를
    사용하십시오 .

지금 HTMLAgilityPack을 다운로드하십시오! ;) 다운로드 링크

이를 통해 HTML을로드하고 구문 분석 할 수 있습니다. 그런 다음 DOM을 탐색하고 모든 속성의 내부 값을 추출 할 수 있습니다. 진지하게, 최대 10 줄의 코드가 필요합니다. 그것은 가장 큰 무료 .net 라이브러리 중 하나입니다.

다음은 샘플입니다.

            string htmlContents = new System.IO.StreamReader(resultsStream,Encoding.UTF8,true).ReadToEnd();

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(htmlContents);
            if (doc == null) return null;

            string output = "";
            foreach (var node in doc.DocumentNode.ChildNodes)
            {
                output += node.InnerText;
            }

Regex.Replace(htmlText, "<.*?>", string.Empty);

protected string StripHtml(string Txt)
{
    return Regex.Replace(Txt, "<(.|\\n)*?>", string.Empty);
}    

Protected Function StripHtml(Txt as String) as String
    Return Regex.Replace(Txt, "<(.|\n)*?>", String.Empty)
End Function

나는 이것을 asp.net 포럼에 게시했지만 여전히 가장 쉬운 솔루션 중 하나 인 것 같습니다. 나는 그것이 가장 빠르거나 가장 효율적이라고 보장하지는 않지만 꽤 안정적입니다. .NET에서는 HTML 웹 컨트롤 개체 자체를 사용할 수 있습니다. 실제로해야 할 일은 문자열을 DIV와 같은 임시 HTML 객체에 삽입 한 다음 내장 'InnerText'를 사용하여 태그에 포함되지 않은 모든 텍스트를 가져 오는 것입니다. 간단한 C # 예제는 아래를 참조하십시오.


System.Web.UI.HtmlControls.HtmlGenericControl htmlDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
htmlDiv.InnerHtml = htmlString;
String plainText = htmlDiv.InnerText;

나는 C #에서 매우 빠른 방법을 작성하여 Regex에서 지옥을 이겼습니다. CodeProject 의 기사 에서 호스팅됩니다 .

이 기능의 장점은 성능이 향상되고 이름이 지정된 번호가 지정된 HTML 엔터티 (예 : &amp;amp;&203;)를 대체하고 주석을 대체하는 기능 등입니다.

CodeProject 관련 기사를 읽으십시오 .

감사합니다.


HtmlAgilityPack을 사용할 수없는 사용자에게는 .NETs XML 리더가 옵션입니다. 올바른 형식의 HTML에서는 실패 할 수 있으므로 항상 regx를 백업으로 사용하십시오. 이것은 빠르지는 않지만 디버깅을 통해 구식 단계에 좋은 기회를 제공합니다.

public static string RemoveHTMLTags(string content)
    {
        var cleaned = string.Empty;
        try
        {
            StringBuilder textOnly = new StringBuilder();
            using (var reader = XmlNodeReader.Create(new System.IO.StringReader("<xml>" + content + "</xml>")))
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Text)
                        textOnly.Append(reader.ReadContentAsString());
                }
            }
            cleaned = textOnly.ToString();
        }
        catch
        {
            //A tag is probably not closed. fallback to regex string clean.
            string textOnly = string.Empty;
            Regex tagRemove = new Regex(@"<[^>]*(>|$)");
            Regex compressSpaces = new Regex(@"[\s\r\n]+");
            textOnly = tagRemove.Replace(content, string.Empty);
            textOnly = compressSpaces.Replace(textOnly, " ");
            cleaned = textOnly;
        }

        return cleaned;
    }

string result = Regex.Replace(anytext, @"<(.|\n)*?>", string.Empty);

Michael Tiptop의 솔루션이 작동하지 않는다고 불평하는 사람들을 위해 .Net4 + 방법이 있습니다.

public static string StripTags(this string markup)
{
    try
    {
        StringReader sr = new StringReader(markup);
        XPathDocument doc;
        using (XmlReader xr = XmlReader.Create(sr,
                           new XmlReaderSettings()
                           {
                               ConformanceLevel = ConformanceLevel.Fragment
                               // for multiple roots
                           }))
        {
            doc = new XPathDocument(xr);
        }

        return doc.CreateNavigator().Value; // .Value is similar to .InnerText of  
                                           //  XmlDocument or JavaScript's innerText
    }
    catch
    {
        return string.Empty;
    }
}

using System.Text.RegularExpressions;

string str = Regex.Replace(HttpUtility.HtmlDecode(HTMLString), "<.*?>", string.Empty);

나는 여기에 제안 된 Regex 기반 솔루션을 살펴 보았으며 가장 사소한 경우를 제외하고는 아무런 자신감도 갖지 못했습니다. 속성의 꺾쇠 괄호는 잘못된 형식의 HTML은 물론 자연스럽게 깨뜨리는 데 필요한 전부입니다. 그리고 같은 엔티티는 &amp;어떻습니까? HTML을 일반 텍스트로 변환하려면 엔터티도 디코딩해야합니다.

So I propose the method below.

Using HtmlAgilityPack, this extension method efficiently strips all HTML tags from an html fragment. Also decodes HTML entities like &amp;. Returns just the inner text items, with a new line between each text item.

public static string RemoveHtmlTags(this string html)
{
        if (String.IsNullOrEmpty(html))
            return html;

        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);

        if (doc.DocumentNode == null || doc.DocumentNode.ChildNodes == null)
        {
            return WebUtility.HtmlDecode(html);
        }

        var sb = new StringBuilder();

        var i = 0;

        foreach (var node in doc.DocumentNode.ChildNodes)
        {
            var text = node.InnerText.SafeTrim();

            if (!String.IsNullOrEmpty(text))
            {
                sb.Append(text);

                if (i < doc.DocumentNode.ChildNodes.Count - 1)
                {
                    sb.Append(Environment.NewLine);
                }
            }

            i++;
        }

        var result = sb.ToString();

        return WebUtility.HtmlDecode(result);
}

public static string SafeTrim(this string str)
{
    if (str == null)
        return null;

    return str.Trim();
}

If you are really serious, you'd want to ignore the contents of certain HTML tags too (<script>, <style>, <svg>, <head>, <object> come to mind!) because they probably don't contain readable content in the sense we are after. What you do there will depend on your circumstances and how far you want to go, but using HtmlAgilityPack it would be pretty trivial to whitelist or blacklist selected tags.

If you are rendering the content back to an HTML page, make sure you understand XSS vulnerability & how to prevent it - i.e. always encode any user-entered text that gets rendered back onto an HTML page (> becomes &gt; etc).


For the second parameter,i.e. keep some tags, you may need some code like this by using HTMLagilityPack:

public string StripTags(HtmlNode documentNode, IList keepTags)
{
    var result = new StringBuilder();
        foreach (var childNode in documentNode.ChildNodes)
        {
            if (childNode.Name.ToLower() == "#text")
            {
                result.Append(childNode.InnerText);
            }
            else
            {
                if (!keepTags.Contains(childNode.Name.ToLower()))
                {
                    result.Append(StripTags(childNode, keepTags));
                }
                else
                {
                    result.Append(childNode.OuterHtml.Replace(childNode.InnerHtml, StripTags(childNode, keepTags)));
                }
            }
        }
        return result.ToString();
    }

More explanation on this page: http://nalgorithm.com/2015/11/20/strip-html-tags-of-an-html-in-c-strip_html-php-equivalent/


Simply use string.StripHTML();

참고URL : https://stackoverflow.com/questions/785715/how-can-i-strip-html-tags-from-a-string-in-asp-net

반응형