问题
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