我有一个这样的 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/