Selecting attribute values with html Agility Pack

You can directly grab the attribute if you use the HtmlNavigator instead.

//Load document from some html string
HtmlDocument hdoc = new HtmlDocument();
hdoc.LoadHtml(htmlContent);

//Load navigator for current document
HtmlNodeNavigator navigator = (HtmlNodeNavigator)hdoc.CreateNavigator();

//Get value from given xpath
string xpath = "//div[@id='topslot']/a/img/@src";
string val = navigator.SelectSingleNode(xpath).Value;

Leave a Comment