convert htmlagilitypack node to htmlelement .net


Question

I have just used htmlagilitypack to extract all link as htmlnode from an html document, but i need this returned from my function as htmlelement

Dim Tags As HtmlNodeCollection = docNode.SelectNodes(strXpath)
  Dim ListResult As New List(Of HtmlElement)
  For Each Tag As HtmlNode In Tags
     ListResult.Add(Tag.Element)
 Next
Return Nothing

How can i do this?

Accepted Answer

I suspect the only way to do it is to create HtmlElement, and then copy attributes and inner HTML from HtmlNode.

Here is an extension method for this; it accepts a reference to a System.Windows.Forms.HtmlDocument instance to create a new HtmlElement:

<System.Runtime.CompilerServices.Extension> _
Public Shared Function ToHtmlElement(node As HtmlNode, doc As System.Windows.Forms.HtmlDocument) As HtmlElement
    Dim element = doc.CreateElement(node.Name)
    For Each attribute As HtmlAttribute In node.Attributes
        element.SetAttribute(attribute.Name, attribute.Value)
    Next
    element.InnerHtml = node.InnerHtml

    Return element
End Function

And to use it you could like this:

Dim browser As New WebBrowser()
browser.Navigate("about::blank")

Dim Tags As HtmlNodeCollection = docNode.SelectNodes(strXpath)
  Dim ListResult As New List(Of HtmlElement)
  For Each Tag As HtmlNode In Tags
     ListResult.Add(Tag.ToHtmlElement(browser.Document))
 Next
Return Nothing

But please note, I'm not too familar with VB.NET, I created code examples for C# first and then translated them to VB,NET.





Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why