Foreach不遍历元素 [英] Foreach not iterating through elements

查看:100
本文介绍了Foreach不遍历元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML文档,并且正在获取基于类的元素.一旦有了它们,我将遍历每个元素并获得更多元素:

I have an HTML document and I'm getting elements based on a class. Once I have them, I'm going through each element and get further elements:

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(content);

var rows = doc.DocumentNode.SelectNodes("//tr[contains(@class, 'row')]");
foreach (var row in rows)
{
    var name = row.SelectSingleNode("//span[contains(@class, 'name')]").InnerText,
    var surname = row.SelectSingleNode("//span[contains(@class, 'surname')]").InnerText,

    customers.Add(new Customer(name, surname));
};

但是,以上内容遍历了各行,但总是检索第一行的文本.

However, the above is iterating through the rows but the always retrieving the text of the first row.

XPath错误吗?

推荐答案

这是XPath中的常见问题解答.每当您的XPath以/开头时,它都会忽略 context元素(在这种情况下,该元素由row引用).无论上下文如何,它都会从根文档节点开始搜索匹配的元素.这就是为什么您的SelectSingleNode()总是返回与整个文档中第一个匹配的元素相同的元素.

This is a FAQ in XPath. Whenever your XPath starts with /, it ignores context element (the element referenced by row variable in this case). It searches for matching elements starting from the root document node regardless of the context. That's why your SelectSingleNode() always return the same element which is the first matched element in the entire document.

您只需在其前面加上一个点(.)即可:

You only need to prepend a dot (.) to make it relative to current context element :

foreach (var row in rows)
{
    var name = row.SelectSingleNode(".//span[contains(@class, 'name')]").InnerText,
    var surname = row.SelectSingleNode(".//span[contains(@class, 'surname')]").InnerText,

    customers.Add(new Customer(name, surname));
}

这篇关于Foreach不遍历元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆