首页 > 解决方案 > 循环节点集合给了我唯一的节点,但是从这些节点中选择节点给了我第一个循环项的结果

问题描述

上下文:使用 HTMLAgilityPack 库,我循环一个 HtmlNodeCollection,打印节点的 HTML 为我提供了我需要的数据,但是当我在 html 中选择节点时,所有这些都给我我选择节点的第一个项目的结果.

将节点 html 编写为 node.InnerHtml 为我提供了它们的唯一 html,所有这些都是正确的,但是当我执行 SelectSingleNode 时,它​​们都给了我相同的数据。

由于项目原因,我不能透露网站。我能说的是,有 17 个节点,它们都是类 k-user-item 的 div。所有项目都是独一无二的,这意味着它们都是不同的。

谢谢您的帮助!

代码:

var nodes = w.DocumentNode.SelectNodes("//div[contains(@class, 'k-user-item')]");

List<Sales> saleList = new List<Sales>();

foreach (HtmlNode node in nodes)
{
    //This line prints correct html, selecting single nodes gives me always the same data of the first item from the loop.
    //Debug.WriteLine(node.InnerHtml);


    string payout = node.SelectSingleNode("//*[@class=\"k-item--buy-date\"]").InnerText;
    string size = node.SelectSingleNode("//*[@class=\"k-panel-title\"]").SelectNodes("//span")[1].InnerText;
    var trNodes = node.SelectNodes("//tr");

    string status = trNodes[1].SelectSingleNode("//b").InnerText;
    string orderId = trNodes[2].SelectNodes("//td")[1].SelectSingleNode("//span").InnerHtml;
    string sellDate = node.SelectSingleNode("//*[@class=\"k-panel-heading\"]").SelectNodes("//small")[1].InnerHtml;

}

标签: c#htmlselectsinglenodeselectnodes

解决方案


这个问题通过在 XPath 中添加一个“.”来解决。开始。

不在 XPath 上添加点意味着节点将在整个文档中搜索,而不仅仅是在确切的节点 html 中搜索。


推荐阅读