將htmlagilitypack節點轉換為htmlelement .net

.net html-agility-pack

我剛剛使用htmlagilitypack從html文檔中提取所有鏈接作為htmlnode,但我需要從我的函數返回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

我怎樣才能做到這一點?

一般承認的答案

我懷疑唯一的方法是創建HtmlElement ,然後從HtmlNode複製屬性和內部HTML。

這是一個擴展方法;它接受對System.Windows.Forms.HtmlDocument實例的引用來創建新的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

要使用它,你可以這樣:

<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

但請注意,我不太熟悉VB.NET,我首先為C#創建了代碼示例,然後將它們翻譯成VB,NET。




許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因