C# HTML Agility Pack - Using a variable in SelectNodes

c# html-agility-pack

Question

What is the syntax for using a variable in the SelectNodes parameters?

For example,

string foo = "bar";

This works

nodes = hd.DocumentNode.SelectNodes("//span[@id='bar']");

But

nodes = hd.DocumentNode.SelectNodes("//span[@id=foo]");

finds no nodes. The issue arises because I can't be sure what the id string will be, so I have to use the variable approach. What is the proper syntax?

The html looks like

<span id="bar">text</span>

Popular Answer

The parameter accepted by SelectNodes is just a string. You could declare a string in advance or just do it all in one line.

string idName = "bar";
string xpath = "//span[@id='" + idName + "']";
nodes = hd.DocumentNode.SelectNodes(xpath);

Or another way to do the same thing with a different string formatter:

string idName = "bar";
nodes = hd.DocumentNode.SelectNodes($"//span[@id='{idName}']");


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