问题
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