Alex Rivera | Logout

Convert string to variable name

Asked 2012-01-04T08:28:04.250
8

I have an XML file, I have a node and I read all ChildNodes. The name of the childNode match to a variable I have to set with the value of this childNode.

In the loop, I'd like set :

  • myvar1 to MyValue1
  • myvar2 to MyValue2

The C# Code :

protected string myvar1;
protected string myvar2;

The XML content look like this :

<parameters>
 <myvar1>MyValue1</myvar1>
 <myvar2>MyValue2</myvar2>
</parameters>

C# set variables :

    foreach (var item in xmlParamInstallation.SelectNodes("parameters")[0].ChildNodes)
    {
        ??????
    }

Any idea ?

Thanks,

UPDATE 1: the value "field" in the loop is null all the time.

public class ParametersTest
{
    public string myvar1 { get; set; }
    public string myvar2 {get; set;}
}

var type = typeof(ParametersTest);
foreach (XmlNode item in xmlParamInstallation.SelectNodes("parameters")[0].ChildNodes)
{

    var field = type.GetField(item.LocalName);
    field.SetValue(field, item.InnerText);
}
Edit
Report

1 Answer

3

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"];
answered 2012-01-04T08:40:46.140

Your Answer