Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

c# - Get a value of an attribute by HtmlAgilityPack

I want to get a value of an attribute by HtmlAgilityPack. Html code:

<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">

I want to get last href attribute.

My c# code:

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;

But that code return first href value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Following XPath selects link elements which have href attribute defined. Then from links you are selecting last one:

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"

You can also use last() XPath operator

var link = doc.DocumentNode.SelectSingleNode("/link[@href][last()]");
var href = link.Attributes["href"].Value;

UPDATE: If you want to get last element which has both itemprop and href attributes, then use XPath //link[@href and @itemprop][last()] or //link[@href and @itemprop] if you'll go with first approach.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...