Newbie Select Question

Topics: Developer Forum, User Forum
Nov 17, 2014 at 3:47 PM
Hi

I have the html below and essentially want to build a Dictionary<string, string> object to use later on. Building the dictionary is no problem, it's the Linq to build a series of id : value nodes that I am struggling with.

<html><body><table>
<tr><td>FirstName</td><td>Bob</td></tr>
<tr><td>LastName</td><td>Smith</td></tr>
<tr><td>Age</td><td></td></tr>
<tr><td>Employed</td><td>Y</td></tr>
</table></body></html>

Desired Results:
        var nodes = doc.DocumentNode.DescendantsAndSelf("tr");  //<==Help here!

        // looping through the nodes:
        // the XPath interfaces can return null when no nodes are found
        Dictionary<string, string> fields = new Dictionary<string, string>();
        if (nodes != null)
        {
            foreach (var node in nodes)
            {
                var id = node.Id;
                var value = node.Attributes["value"].Value;
                fields.Add(id, value);
            }
        }
Thanks in advance
Nov 17, 2014 at 5:11 PM
Is the below weak - it sort of gets the first two cells - but if feels really gludgy!
        foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))
        {
            foreach (HtmlNode row in table.SelectNodes("tr"))
            {
                int i = 0;
                string id = string.Empty;
                string value = string.Empty;
                foreach (HtmlNode cell in table.SelectNodes("td"))
                {
                    if (i == 0)
                    {
                        id = cell.InnerText;
                    }

                    if (i == 1)
                    {
                        value = cell.InnerText;
                    }
                    i++;
                }
                formFields.Add(id, value);
            } 
        }