c# xml SelectSingleNode issue unable to use variable in node name

104 Views Asked by At

Have the following line of code

 // Load screen containers
serverTest = document.SelectSingleNode("Server/". this.serverName . "/test").InnerText;

C# isn't liking the "." concatenation character, not sure what to do here.

serverTest is a property of my class btw

3

There are 3 best solutions below

0
ScaryMinds On

Oops was using PHP concatenation character, was using that language an hour ago.

Could one of the mods delete this one, sorry for taking up space.

0
dotnetstep On

You have to do something like this.

document.SelectSingleNode(@"Server/" + this.serverName + @"/test").InnerText;
0
NitinSingh On

For string concatenation, use the "+" plus operator or maybe string.Format if it contains a lot of variables

document.SelectSingleNode(@"Server/" + this.serverName + @"/app").InnerText;

For lots of variables (multiple parameters may be usable once you require attribute based retrieval of nodes):-

// for [Server/localhost/App/MyApp/Module/Admin/Action/Test"

var location = string.Format(@"Server/{0}/App/{1}/Module/{2}/Action/{3}", this.serverName, this.appName, this.moduleName, this.actionName);
document.SelectSingleNode(location).InnerText;

By separating the location from the retrieval function, you can easily debug it and log in case any value is improper. Also makes code readable IMHO. However for a single value, using concatenation inline can be ok in most cases.