vb.net HtmlAgilityPack Insert string after div

.net html html-agility-pack vb.net

Question

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
4
8/15/2014 9:43:17 PM

Accepted Answer

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.

4
8/16/2014 12:29:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow