Voglio ottenere un valore di un attributo da HtmlAgilityPack. Codice 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">
Voglio ottenere l'ultimo attributo href.
Il mio codice 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;
Ma quel codice restituisce il primo valore href.
Seguendo XPath seleziona gli elementi di link
che hanno definito l'attributo href
. Quindi dai link che stai selezionando l'ultimo:
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"
Puoi anche usare last()
operatore XP last()
var link = doc.DocumentNode.SelectSingleNode("/link[@href][last()]");
var href = link.Attributes["href"].Value;
AGGIORNAMENTO: Se vuoi ottenere l'ultimo elemento che ha sia itemprop
che href
, usa XPath //link[@href and @itemprop][last()]
o //link[@href and @itemprop]
se vuoi andare con il primo approccio.