VB.net 用 HTML 字符串填充文本框

VB.net Fill Textbox with HTML string

我有一个来自 HTML 启用的电子邮件的字符串,如下所示:

</div><span color="red">Hi how are you?!</span></div><table><tr><td>Company Information</td></tr></table>

等等[它是一长串东西,但你明白了。有<div>..<spans>..<table>等等。

我想在文本框中显示格式为 html 的文本 [这将基于 <table>..<span> 等格式同时从文本框的文本中删除 <span> 等的实际文本。

我需要这样做,因为我收到一个页面错误,因为它读取 <span> 等是一个安全问题。

我目前阅读全文和排除问题的方式是这样的:

        If Not DsAds.Tables(0).Rows(0).Item(0) Is DBNull.Value Then
            Dim bodyInitial As String = DsAds.Tables(0).Rows(0).Item(0).ToString()

            Dim newbody As String = bodyInitial.Replace("<br>", vbNewLine)
            newbody = newbody.Replace("<b>", "")
            newbody = newbody.Replace("</b>", "")
            Bodylisting.Text = newbody
        End If

我试图合并以下内容:

Dim bodyInitial As String = DsAds.Tables(0).Rows(0).Item(0).ToString()
        Dim myEncodedString As String
        ' Encode the string.
        myEncodedString = bodyInitial.HttpUtility.HtmlEncode(bodyInitial)

        Dim myWriter As New StringWriter()
        ' Decode the encoded string.
        HttpUtility.HtmlDecode(bodyInitial, myWriter)

但是我在使用 HTTpUtility 和字符串时遇到错误

问题:

所以我的问题是,有没有办法真正看到 HTML 格式并以这种方式填充文本框,还是我必须坚持使用我的 .Replace 方法?

<asp:TextBox ID="Bodylisting" runat="server" style="float:left; margin:10px; padding-bottom:500px;" Width="95%" TextMode="MultiLine" ></asp:TextBox>

我建议你调查一下 HtmlAgilityPack。该库包含一个解析器,使您能够 'select' <span> 标签。拥有它们后,您可以将它们剥离,或获取 InnerHtml 并进行进一步处理。这是我如何用它做类似事情的一个例子。

    Private Shared Function StripHtml(html As String, xPath As String) As String
        Dim htmlDoc As New HtmlDocument()
        htmlDoc.LoadHtml(html)
        If xPath.Length > 0 Then
            Dim invalidNodes As HtmlNodeCollection = htmlDoc.DocumentNode.SelectNodes(xPath)
            If Not invalidNodes Is Nothing Then
                For Each node As HtmlNode In invalidNodes
                    node.ParentNode.RemoveChild(node, True)
                Next
            End If
        End If
        Return htmlDoc.DocumentNode.WriteContentTo()


    End Function