简体   繁体   中英

Getting inner text values from a select list with C#

I want to extract option values as well as the text between the option tags from a select list.

body>
<select name="country" id="id_country">
    <option value="">Select a country...</option>
    <option value="AF">Afghanistan</option>
    <option value="AX">Åland Islands</option>
    <option value="AL">Albania</option>
    <option value="DZ">Algeria</option>
    <option value="AS">American Samoa</option>
    <option value="AD">Andorra</option>
    <option value="AO">Angola</option>

I have tried the following which makes sense to me.

 HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(sb.ToString());

            var values = doc.DocumentNode.Descendants("option").Select(n => new
             {
                 Value = n.Attributes["value"].Value,
                 Text = n.InnerHtml,
             }).ToList();

and managed to get the option value but not the country name between the tags.

return this instead.

 Value="AF", Text="",
Value="AX", Text="",

etc. How can I return the values as well?

应该使用n.InnerText而不是InnerHtml。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM