Get all attribute values of given tag with Html Agility Pack

别等时光非礼了梦想. 提交于 2020-01-01 19:37:08

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/2462552/get-all-attribute-values-of-given-tag-with-html-agility-pack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!