Skip to content Skip to sidebar Skip to footer

Foreach Not Iterating Through Elements

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.HtmlDocu

Solution 1:

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));
}

Solution 2:

What about using LINQ?

var customers = rows.Select(row =>newCustomer(Name = row.SelectSingleNode("//span[contains(@class, 'name')]").InnerText, Surname = row.SelectSingleNode("//span[contains(@class, 'surname')]").InnerText)).ToList();

Post a Comment for "Foreach Not Iterating Through Elements"