Using Htmlagility pack getting attribute values

c# html-agility-pack html-parsing

Question

Using Htmlagilitypack I can get the attribute value for one tag by using following code:

public string parseinput(HtmlDocument HtmlDocument)
{
     try
     {
            return HtmlDocument.DocumentNode.SelectSingleNode("//input[@type=""text""]").Attributes["value"].Value;
     }

     catch (Exception ex)
     {
          string x= ex.ToString();
            return "Error is... '"+x+"'" ;
     }
 }

When it gets first value, it stops executing and gives that value, but I need to get all those text type values as output.

For this what do I need to do?

Accepted Answer

you need SelectNodes instead of SelectSingleNode

return String.Join(",", HtmlDocument.DocumentNode.SelectNodes("//input[@type=""text""]")
                         .Select(n=>n.Attributes["value"].Value)

If you need both input type and value

var inputs = doc.DocumentNode.SelectNodes("//input").Select(n => new { 
                 Type = n.Attributes["type"].Value, Value = n.Attributes["value"].Value }).ToList();


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