重复循环不会遍历所有元素

时间:2018-09-12 17:32:15

标签: c#

我在一组节点中使用重复循环,但是输出始终是foreach的第一个输入...

var all_accounts_elements = content.GetCollectionNode(
    "//div[@class='box-list-item text-c js-list-item']");

foreach (HtmlNode account_element in all_accounts_elements)
{
    //for debug only
    var copy = account_element;

    var account = new InstagramAccount();

    //for debug only
    var debug = copy.SelectSingleNode("//*[@class='title']");
    Debug.WriteLine(debug.InnerText);

    account.AccountName = account_element.SelectSingleNode("//*[@class='title']")
        .InnerText.ToTilteCase().Trim();
    account.AddedData = account_element.SelectSingleNode("//*[@class='sub']")
        .InnerText.Trim();
    account.Edit = account_element.SelectSingleNode("//*[@class='context-menu']")
        .InnerText.Trim();
    account.Message = account_element.SelectSingleNode("//*[@class='quick-info']")
        .InnerText.Trim();

    accountsList.Add(account);

}

集合:enter image description here

第一个元素:enter image description here

第二个元素:enter image description here

输出:

jonisbarcelos
jonisbarcelos

1 个答案:

答案 0 :(得分:0)

您的XPath选择器告诉HTMLAgilityPack查看整个文档。尝试查看后代:

account.AccountName = account_element.SelectSingleNode("descendant::div[@class='title']")
    .InnerText.ToTilteCase().Trim();
account.AddedData = account_element.SelectSingleNode("descendant::div[@class='sub']")
    .InnerText.Trim();
account.Edit = account_element.SelectSingleNode("descendant::div[@class='context-menu']")
    .InnerText.Trim();
account.Message = account_element.SelectSingleNode("descendant::div[@class='quick-info']")
    .InnerText.Trim();