将 htmlagilitypack 节点转换为 htmlelement .net

发布于 2025-01-08 14:24:14 字数 326 浏览 0 评论 0原文

我刚刚使用 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

我该如何执行此操作?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦在深巷 2025-01-15 14:24:14

我怀疑唯一的方法是创建 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

要使用它,您可以像这样:

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

但请注意,我由于不太熟悉 VB.NET,我先为 C# 创建了代码示例,然后将它们翻译为 VB、NET。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文