How to get attribute of child anchor with HtmlAgilityPack?

c# html-agility-pack

Question

I am learning HtmlAgilitiPack and I want ask you, how to get value(I want get this value):

From HTML page:

<div id="js_citySelectContainer" class="select_container city_select shorten_text replaced"> 
<span class="dropDownButton ownCity coords">
<a>i want get this value</a>
</span>
</div>

C# code:

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
Console.writeln(echo i want get this value);

I tried:

doc.DocumentNode.Descendants("span").Where(s => s.GetAttributeValue("class", "") == "dropDownButton ownCity coords").First().InnerText;

But it doesnt work, can you help me? Thank you.

Accepted Answer

You can use the XPATH syntax:

var span = doc.DocumentNode.SelectSingleNode("//span[@class='dropDownButton ownCity coords']");
var anchorText = span.ChildNodes["a"].InnerText;

You can also use LINQ:

var anchorTexts = 
    from span in doc.DocumentNode.Descendants("span")
    where span.GetAttributeValue("class", "") == "dropDownButton ownCity coords" 
    from anchor in span.Descendants("a") 
    select anchor.InnerText;
string anchorText = anchorTexts.FirstOrDefault();

Popular Answer

I think that you are trying to get the span text, you need the a text

try this

doc.DocumentNode.Descendants("span")
.Where(s => s.GetAttributeValue("class", "") == "dropDownButton ownCity coords")
.First().Descendants("a").First().InnerText;



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why