【问题标题】:Can't convert HTML to plain text: ASP.net无法将 HTML 转换为纯文本:ASP.net
【发布时间】:2016-12-11 13:11:45
【问题描述】:

我有以下从 sql server 检索到的 HTML 文本。

"<span style="color: rgb(36, 39, 41); font-family: Arial, &quot;Helvetica Neue&quot;, Helvetica, sans-serif; font-size: 15px; background-color: rgb(255, 255, 255);">So, first method looks nice and it's easy but is there is any simpler way to write the second function? Both are working well and giving a correct output.</span>" 

我想将 html 转换为纯文本并将其设置在 asp.net 中的标签上。

要做到这一点:

  1. 我已从 Dataset 中的 sql server 检索到数据。
  2. 设置上面检索到的标签

         <h3 id="lblqNotes" runat="server" class="text-questiondata" style="color:#1E90FF">
       </h3>
    

在后面的代码中:

  lblqNotes.InnerText = System.Net.WebUtility.HtmlDecode(values[2]);

但标签上的输出仍然是 html 代码,而不是纯文本。

感谢您的帮助。

【问题讨论】:

  • HtmlEncode 不用于转换为纯文本。是吗?
  • 朋友,你为什么不看看它的作用?
  • "HTML 编码确保文本在浏览器中正确显示,并且不会被浏览器解释为 HTML。例如,如果文本字符串包含小于号 (),浏览器会将这些字符解释为 HTML 标记的左括号或右括号。当这些字符被 HTML 编码时,它们将转换为字符串 < 和 >,这会导致浏览器显示小于号和大于正确签名。”
  • 明白。但这不是我要找的。我需要做的是将其转换为纯文本。例如:HTML hello。输出应该是粗体的 hello

标签: c# html asp.net .net


【解决方案1】:

您可以使用XmlDocument

    static void Main(string[] args)
    {
        var xmlDocument = new XmlDocument();
        var html = @"<span style=""color: rgb(36, 39, 41); font - family: Arial, &quot; Helvetica Neue&quot;, Helvetica, sans - serif; font - size: 15px; background - color: rgb(255, 255, 255); "">So, first method looks nice and it's easy but is there is any simpler way to write the second function? Both are working well and giving a correct output.</span>";
        xmlDocument.LoadXml(html);

        var text = xmlDocument.InnerText;
        // So, first method looks nice and it's easy but is there is any simpler way to write the second function? Both are working well and giving a correct output.
    }

【讨论】:

  • 太棒了。做最简单的事。就一个问题。如何将“@”与在 LoadXmL 方法中具有 html 代码的变量一起使用,例如 xmlDocument.LoadXml(@)??
  • @ 只是一个逐字字符串,我已更新问题以提取该变量
  • 可行,但在我的情况下,我从数据库中提取数据并将数据存储到变量中。那么我如何将 @ 放在那个变量上呢?我试过这个字符串 var= @values[2];但它会引发错误。这里的 values[2] 有 html 代码。
  • 刚刚删除了@,可以很好地解决您的问题
  • 但是如果我在一个变量中有多个标签,像这样: 我有一个代表年龄的字符串,格式为:
    , 它抛出错误说有多个根元素。对此有何建议?
【解决方案2】:

尝试此代码使用正则表达式去除 Html:output = Regex.Replace(source, "&lt;[^&gt;]*&gt;", string.Empty);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-12
  • 2014-09-08
  • 2018-03-17
  • 1970-01-01
  • 2014-04-21
  • 1970-01-01
  • 2010-09-22
相关资源
最近更新 更多