html - 使用 Html Agility Pack 剥离所有 html 标签

标签 html vb.net html-agility-pack strip

我有一个这样的 html 字符串:

<html><body><p>foo <a href='http://www.example.com'>bar</a> baz</p></body></html>

我想去掉所有的 html 标签,这样得到的字符串就变成了:

foo bar baz

从 SO 的另一篇文章中我想出了这个函数(它使用 Html Agility Pack):

  Public Shared Function stripTags(ByVal html As String) As String
    Dim plain As String = String.Empty
    Dim htmldoc As New HtmlAgilityPack.HtmlDocument

    htmldoc.LoadHtml(html)
    Dim invalidNodes As HtmlAgilityPack.HtmlNodeCollection = htmldoc.DocumentNode.SelectNodes("//html|//body|//p|//a")

    If Not htmldoc Is Nothing Then
      For Each node In invalidNodes
        node.ParentNode.RemoveChild(node, True)
      Next
    End If

    Return htmldoc.DocumentNode.WriteContentTo
  End Function

不幸的是,这并没有返回我所期望的,而是给出了:

bazbarfoo

请问我哪里出错了 - 这是最好的方法吗?

问候和愉快的编码!

更新:根据下面的回答,我想到了这个功能,可能对其他人有用:

  Public Shared Function stripTags(ByVal html As String) As String
    Dim htmldoc As New HtmlAgilityPack.HtmlDocument
    htmldoc.LoadHtml(html.Replace("</p>", "</p>" & New String(Environment.NewLine, 2)).Replace("<br/>", Environment.NewLine))
    Return htmldoc.DocumentNode.InnerText
  End Function

最佳答案

为什么不直接返回 htmldoc.DocumentNode.InnerText 而不是删除所有非文本节点?它应该给你你想要的。

关于html - 使用 Html Agility Pack 剥离所有 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3140919/

相关文章:

c# - 获取下一个同级节点中相同位置的节点

html - 制作 div 的响应式大图

javascript - 使用 angular-modal-service (AngularJS) 自定义模式

javascript - 鼠标位置仅在第一帧读取

php - 在php中指定图像的宽度和高度

javascript - 从类库调用 Javascript

asp.net - 根据 bool 结果进行函数链接

vb.net - 多线程和套接字/TCP [VB.NET]

c# - System.Reflection.TargetInitationException 错误 (C#)

c# - SelectNodes 特定于一个节点