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

Posted

技术标签:

【中文标题】如何在 C# 中将 HtmlEncode/HtmlDecode 转换为纯文本?【英文标题】:How to convert HtmlEncode/HtmlDecode to pure text in C#? 【发布时间】:2015-05-23 11:35:48 【问题描述】:

我使用的是CKEditor ASP.NET 版本并适应我的写作空间。单击btn_Post 按钮时,应在此编辑器字段中发布书面文本。我想在 C# 中获取此文本,因为用于保存在数据库中。于是我搜索了如何使用(here),找到了使用htmlEncode的方法。这是我找到的代码。

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

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 

但问题是,我需要保存没有 html 代码的文本。如您所见,所有变量都显示 html 代码。如何将此结果更改为纯文本1234

【问题讨论】:

我希望这将帮助您 [删除字符串中的 HTML 标记][1] [如何在 ASP.NET 中从字符串中删除 HTML 标记?][2] [从字符串中删除 HTML 标记,包括&nbsp 在 C#][3] [1]: ***.com/questions/4878452/remove-html-tags-in-string [2]: ***.com/questions/785715/… [3]: ***.com/questions/19523913/… @RomanBezrabotny 哦,您会找到很多参考资料。谢谢 ;) 我需要阅读更多内容 只是想知道,如果您只想拥有文本,为什么还需要 CKEditor?那么一个简单的文本区域不是更好吗?或者,如果您只需要 HTML 文本之外的纯文本,那么我理解 【参考方案1】:

你可以用这个方法

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;
        

或使用HTML Agility Pack 删除所有 HTML 标记。

【讨论】:

找不到Regex怎么办?? \s "always" 已经包含了 \r 和 \n,因此不需要单独包含它们。 (“总是”,因为某些实现可能不包括它们,但所有经常使用的都做,而常规的 .NET 尤其如此)。

以上是关于如何在 C# 中将 HtmlEncode/HtmlDecode 转换为纯文本?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 C# 中将结构转换为字节数组?

如何在 C# 中将更新参数添加到 SQLDataSource

如何在 C# 中将字符串转换为 DateTime?

如何在 C# 中将固定字节/字符 [100] 转换为托管字符 []?

如何在 C# 中将字符串转换为字节 []

如何在 C# 中将字节 [] 转换为日期时间?