Quiero obtener un valor de un atributo por HtmlAgilityPack. Código HTML:
<link href="style.css">
<link href="anotherstyle.css">
<link href="anotherstyle2.css">
<link itemprop="thumbnailUrl" href="http://image.jpg">
<link href="anotherstyle5.css">
<link href="anotherstyle7.css">
Quiero obtener el último atributo href.
Mi código c #:
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument htmldoc = web.Load(Url);
htmldoc.OptionFixNestedTags = true;
var navigator = (HtmlNodeNavigator)htmldoc.CreateNavigator();
string xpath = "//link/@href";
string val = navigator.SelectSingleNode(xpath).Value;
Pero ese código devuelve el primer valor href.
El siguiente XPath selecciona elementos de link
que tienen el atributo href
definido. Luego, desde los enlaces que seleccionas el último:
var link = doc.DocumentNode.SelectNodes("//link[@href]").LastOrDefault();
// you can also check if link is not null
var href = link.Attributes["href"].Value; // "anotherstyle7.css"
También puedes usar last()
operador last()
XPath.
var link = doc.DocumentNode.SelectSingleNode("/link[@href][last()]");
var href = link.Attributes["href"].Value;
ACTUALIZACIÓN: Si desea obtener el último elemento que tiene los atributos itemprop
y href
, use XPath //link[@href and @itemprop][last()]
o //link[@href and @itemprop]
si lo desea. Ir con la primera aproximación.