drj3122 drj3122 - 3 months ago 41
C# Question

C# HTML Agility Pack - Using a variable in SelectNodes

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>

Answer

Use it Like this:

string foo = "bar";

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