Get all attribute values of given tag with Html Agility Pack

c# html html-agility-pack xml xpath

Question

I want to get all values of 'id' attribute of 'span' tag with html agility pack. But instead of attributes I got tags themself. Here's the code

        private static IEnumerable<string> GetAllID()
        {
            HtmlDocument sourceDocument = new HtmlDocument();
            sourceDocument.Load(FileName);
            var nodes = sourceDocument.DocumentNode.SelectNodes(
                 @"//span/@id");
            return nodes.Nodes().Select(x => x.Name);
        }

I'll appreciate if someone tells me what's wrong here.

Accepted Answer

try

var nodes = sourceDocument.DocumentNode.SelectNodes("//span[@id]");
List<string> ids = new List<string>(nodes.Count);

if(nodes != null)
{
    foreach(var node in nodes)
    {
        if(node.Id != null)
        ids.Add(node.Id);
    }
}

return ids;



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why