简体   繁体   English

如何在C#中将HtmlEncode / HtmlDecode转换为纯文本?

[英]How to convert HtmlEncode/HtmlDecode to pure text in C#?

I used CKEditor ASP.NET version and adjust to my writing space. 我使用CKEditor ASP.NET版本并调整到我的写作空间。 When click btn_Post button, then should post written text in this editor field. 单击btn_Post按钮时,应在此编辑器字段中发布书面文本。 I want to get this text in C# because for saving at database. 我想在C#中获取此文本,因为要保存在数据库中。 So I searched how to use( here ) and found the way using HtmlEncode. 所以我搜索了如何使用( 这里 ),并找到了使用HtmlEncode的方法。 Here is codes what I found. 这是我发现的代码。

asp 天冬氨酸

<div>
  <CKEditor:CKEditorControl ID="CKEditor1" BasePath="/ckeditor/" runat="server">
  </CKEditor:CKEditorControl>
</div>
<div style="margin-top:10px; float:right;">
  <asp:button ID="btn_Post" runat="server" Text="등록하기" CssClass="btn_Post" onclick="btn_Post_Click" />    
</div>

CS CS

string str = CKEditor1.Text;
string str1 = Server.HtmlEncode(str);
string str2 = Server.HtmlDecode(str);
//str = <p>1234</p>\r\n
//str1 = &lt;p&gt;1234&lt;/p&gt;\r\n
//str2 = <p>1234</p>\r\n 

But the problem is, I need to save text with none html codes. 但是问题是,我需要保存没有html代码的文本。 As you can see, all variable shows html code. 如您所见,所有变量都显示html代码。 How can I change this result to pure text 1234 ? 如何将结果更改为纯文本1234

You can use this method 您可以使用此方法

public static string RemoveHTMLTags(string content)
        {
            var cleaned = string.Empty;
            try
            {
                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;
            }
            catch
            {
                //A tag is probably not closed. fallback to regex string clean.

            }

            return cleaned;
        }

Or use HTML Agility Pack to remove all HTML tags. 或使用HTML Agility Pack删除所有HTML标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM