Select any element by class - xpath

c# html-agility-pack

Question

How can I select any element by class/name using xpath?

var nodeByClass = doc.DocumentNode.SelectSingleNode("//[@class='class_name']");
var nodeName = doc.DocumentNode.SelectSingleNode("//[@name='element_name']");

I got a exception

The expression must be evaluated for a set of nodes.

Popular Answer

You're missing a location step after the //, as the predicate on its own is not allowed.

var nodeByClass = doc.DocumentNode.SelectSingleNode("//*[@class='class_name']");
var nodeName = doc.DocumentNode.SelectSingleNode("//*[@name='element_name']");

short-hand for:

var nodeByClass = doc.DocumentNode.SelectSingleNode("//self::node()[@class='class_name']");
var nodeName = doc.DocumentNode.SelectSingleNode("//self::node()[@name='element_name']");


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