vb.net HtmlAgilityPack Insert string after div

孤街浪徒 提交于 2019-12-23 13:20:51

问题


I'm trying to inset some of my own html directly after the end of a div. This div has other div inside of it.

    Dim HtmlNode As HtmlNode = HtmlNode.CreateNode("<span class=""label"">Those were the friends</span>")
    Dim FriendDiv = htmldoc.DocumentNode.SelectSingleNode("//div[@class='profile_friends']")
    Dim NewHTML As HtmlNode = htmldoc.DocumentNode.InsertAfter(HtmlNode, FriendDiv)

Every time I run that code I get an exception Node "<div class="profile_topfriends"></div>" was not found in the collection


回答1:


Similar to XmlNode's InsertAfter(), you need to call this method on the common parent of referenced node and to be inserted node. Try something like this :

Dim NewHTML As HtmlNode = FriendDiv.ParentNode.InsertAfter(HtmlNode, FriendDiv)

Worked fine for me. Here is a simple test I did in C# (translated to VB) :

Dim html = "<body><div></div></body>"
Dim doc As New HtmlDocument()
doc.LoadHtml(html)
Dim div = doc.DocumentNode.SelectSingleNode("//div")
Dim span = HtmlNode.CreateNode("<span class=""label"">Those were the friends</span>")
Dim newHtml = div.ParentNode.InsertAfter(span, div)
Console.WriteLine(XDocument.Parse(doc.DocumentNode.OuterHtml).ToString())

The <span> appears after <div> in console.



来源:https://stackoverflow.com/questions/25334644/vb-net-htmlagilitypack-insert-string-after-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!