Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vb.net HtmlAgilityPack Insert string after div

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

like image 414
user2005848 Avatar asked Aug 15 '14 21:08

user2005848


1 Answers

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.

like image 166
har07 Avatar answered Oct 14 '22 08:10

har07