j'ai ce code
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
mais j'obtiens une erreur Object reference not set to an instance of an object.
le document contient au moins une balise anchor? Comment puis-je vérifier si un attribut existe?
J'ai essayé cela if link.HasAttributes("title") then
et obtenir une autre erreur
Public ReadOnly Property HasAttributes() As Boolean' has no parameters and its return type cannot be indexed.
Si HtmlAgilityPack supporte ce sélecteur XPATH, vous pouvez remplacer //a
par //a[@href]
For Each link as HtmlNode In root.SelectNodes("//a[@href]")
doSomething()
Next
Sinon, vous pouvez utiliser la propriété 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
En outre, vous pouvez vérifier les attributs: link.Attributes ["title"] si null, alors n’a pas d’attribut. Même lien.Attributs ["href"] et etc.
La propriété link.HasAttributes montre seulement que cette balise a un attribut, c'est une valeur bool.