2

Resolved

HtmlNode.Ancestors() method does not include ParentNode

description

The HtmlNode.Ancestors() method does not include the parent node in the list of ancestors returned. The first ancestor returned is the grandparent node, then the great grandparent node etc. In other words the parent node is skipped.
 
    /// <summary>
    /// Returns a collection of all ancestor nodes of this element.
    /// </summary>
    /// <returns></returns>
    public IEnumerable<HtmlNode> Ancestors()
    {
        HtmlNode node = ParentNode;
        while (node.ParentNode != null)
        {
            yield return node.ParentNode;
            node = node.ParentNode;
        }
    }
 
This is inconsistent with the HtmlNode.Ancestors(string name) method, which does return the parent (assuming the name matches the name parameter).
 
Both overloads of HtmlNode.AncestorsAndSelf also return the parent node.
 
A simple fix is to initialise the node variable with this rather than ParentNode.

comments

tom103 wrote Aug 12, 2012 at 8:23 PM

I just stumbled on this bug... I'm surprised it is still there, more that one year after being reported. And it seems quite easy to fix ;)

DarthObiwan wrote Aug 23, 2012 at 2:27 PM

This has been fixed in source control at revision: 99300

This will be included in the next release

I had missed this too. Thanks for bumping it back up