如何获取2个单独的类值节点并将其写入datatable

如何获取2个单独的类值节点并将其写入datatable

我似乎在名称循环上一切正常,但是在加载时,会将玩家名称分配给datagridview中的名称列,但是位置列似乎不断循环,并且没有为每个玩家关联正确的值。

public void button7_Click(object sender, EventArgs e)
{
    DataTable dt6 = new DataTable();
    dt6.Columns.Add("Name");
    dt6.Columns.Add("Position");
    DataRow row;

    var doc = new HtmlWeb().Load("https://www.numberfire.com/nba/daily-fantasy/daily-basketball-projections");
    foreach (HtmlNode node1 in doc.DocumentNode.SelectNodes(".//span[@class='player-info']//a[2]"))
    {
        foreach (HtmlNode node2 in doc.DocumentNode.SelectNodes(".//span[@class='player-info--position']"))
        {
            row = dt6.NewRow();
            row["Name"] = node1.InnerHtml.Trim();
            row["Position"] = node2.InnerHtml.Trim();
            dt6.Rows.Add(row);
        }
    }
    dataGridView4.DataSource = dt6;
}

最佳答案

弄清楚了:

    public void button7_Click(object sender, EventArgs e)
    {

        DataTable dt6 = new DataTable();
        dt6.Columns.Add("Name");
        dt6.Columns.Add("Position");
        DataRow row;



        var doc = new HtmlWeb().Load("https://www.numberfire.com/nba/daily-fantasy/daily-basketball-projections");


        foreach (HtmlNode node1 in doc.DocumentNode.SelectNodes("//span[@class='player-info']"))
        {
            row = dt6.NewRow();

            foreach (HtmlNode node in node1.SelectNodes(".//a"))
            {

                row["Name"] = node.InnerHtml.Trim();

            }
                foreach (HtmlNode node2 in node1.SelectNodes(".//span[@class='player-info--position']"))
                {

                    row["Position"] = node2.InnerText.Trim();

                }
            dt6.Rows.Add(row);
        }
        dataGridView4.DataSource = dt6;
        }

关于c# - C#如何获取2个单独的类值节点并将其写入datatable/dgv,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55305770/

10-12 15:27