Convert string to variable name Convert string to variable name xml xml

Convert string to variable name


You can do it using Reflection:

var type = typeof(SomeClass);var field = type.GetField(item.Name);field.SetValue(null, item.InnerText);

RE: UPDATE 1

var parameters = new ParametersTest();var type = parameters.GetType();var s = @"<parameters>            <MyVar1>MyValue1</MyVar1>            <MyVar2>MyValue2</MyVar2>           </parameters>";var xmlParamInstallation = new XmlDocument();xmlParamInstallation.LoadXml(s);foreach (XmlNode item in xmlParamInstallation.SelectNodes("parameters")[0].ChildNodes){    var field = type.GetProperty(item.LocalName);    field.SetValue(parameters, item.InnerText, null);}


If you are seeking to assign variables based on the names of nodes in XML, you have at least a couple options:

  • Deserialize the XML structure into an object with corresponding member names
  • Populate the variables using reflection
  • Populate the variables using dynamic method calls/expression trees that know how to read the contents of the XML node into an object property.

All of these approaches suggest a more object-oriented approach to the problem then just populating a few variables, but it would be easy to create a lightweight structure with the appropriate members which is populated by reading the XML document.

You could also use a key-based collection (like a Dictionary<string, string>) to store the values if you are just looking to build a simple name/value collection from the source XML.


If you put the names and values in a dictionary, you can easily get the values by name:

Dictionary<string, string> parameters =  xmlParamInstallation.SelectNodes("parameters")[0].ChildNodes  .ToDictionary(n => n.Name, n => n.InnerText);myvar1 = parameters["myvar1"];myvar2 = parameters["myvar2"];