我有這個代碼

Dim htmldoc As HtmlDocument = New HtmlDocument()
htmldoc.LoadHtml(strPageContent)
Dim root As HtmlNode = htmldoc.DocumentNode

For Each link As HtmlNode In root.SelectNodes("//a")
    If link.HasAttributes("href") Then doSomething() 'this doesn't work because hasAttributes only checks whether an element has attributes or not
Next

但我得到一個錯誤Object reference not set to an instance of an object.

該文件至少包含一個錨標籤?我如何檢查屬性是否退出?

我試過這個if link.HasAttributes("title") then又得到另一個錯誤

Public ReadOnly Property HasAttributes() As Boolean' has no parameters and its return type cannot be indexed.

一般承認的答案

如果HtmlAgilityPack支持這個XPATH選擇器,你可以用//a //a[@href]替換//a

For Each link as HtmlNode In root.SelectNodes("//a[@href]")
    doSomething()
Next

否則,您可以使用Attributes屬性:

For Each link as HtmlNode In root.SelectNodes("//a")
    If link.Attributes.Any(Function(a) a.Name = "href") Then doSomething()
Next

熱門答案

Dim htmldoc As HtmlDocument = New HtmlDocument()
htmldoc.LoadHtml(strPageContent)
Dim root As HtmlNode = htmldoc.DocumentNode

var nodes = root.SelectNodes("//a[@href and @title]")
if (nodes <> Null) Then
    For Each link As HtmlNode In nodes
        If link.HasAttributes("href") Then doSomething() 'this doesn't work because hasAttributes only checks whether an element has attributes or not
    Next
end if

此外,您可以檢查屬性:link.Attributes [“title”]如果為null,則沒有屬性。相同的鏈接。屬性[“href”]等。

屬性link.HasAttributes只顯示該標籤有任何屬性,它是bool值。



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow