如何在VB.NET中的注释掉的代码HtmlAgilityPack中获取元素

时间:2014-06-20 15:30:01

标签: vb.net html-agility-pack

有没有办法在<!-- -->注释块内的html上使用HtmlAgilityPack?例如,如何定位块内的"//div.[@class='theClass']"的内部文本,如下所示:

<!-- <div class="theClass'>Hello I am <span class="theSpan">some text.</span> </div>-->

所以我得到了

Hello I am some text.

我问的原因是因为我一直发现这会一直返回NULL,因为div的内容是注释:

htmlnodes = htmldoc.DocumentNode.SelectNodes("//div[@class='theClass']")

1 个答案:

答案 0 :(得分:2)

不幸的是,XPath将注释节点内容视为纯文本,意味着您无法像公共节点一样查询内容。

一种可能的方法是将评论节点内容解析为另一个HtmlDocument,以便您可以从中进行查询,例如:

'get desired comment node'
Dim htmlnode As HtmlNode = htmldoc.DocumentNode.SelectSingleNode("//comment()[contains(., theClass)]")

Dim comment As New HtmlDocument()
'remove the outer <!--  --> so we have clean content'
comment.LoadHtml(htmlnode.InnerHtml.Replace("<!--", "").Replace("-->", ""))
'here you can use common XPath query again'
Dim result As HtmlNode = comment.DocumentNode.SelectSingleNode("//div[@class='theClass']")

'following line will print "Hello I am some text."'
Console.WriteLine(result.InnerText)