I need to load settings from a file, the file is essentially xml - each 'setting' is an element and has attributes (name, type & value).
I loop through each 'setting' and need to create objects accordingly.
How do I dynamically create objects of the type specified by each 'setting' and initialise them to the specified value?
Loading
graemePosted Oct 20, 2009, 8:44 AM
Example: The file tells me there is a setting named 'Setting1', it is of type 'System.Int32' and the value is '1'.
I can get a Type object as I have the fully qualified type name (System.Int32) and I have the value that the object should ultimately have (1) - although this is in String form.
In this instance I need a way of instantiating an int object and setting it's value to 1 - this method must, however, work for any type - I don't want to have to code tests for every conceivable type, for example:
Nilanka DharmadasaPosted Oct 20, 2009, 7:00 AM
Or you can temporily store the settings as Objects and use 'GetType()' method to get the type.
Then you can create the objects.
graemePosted Oct 20, 2009, 5:41 AM
Nilanka DharmadasaPosted Oct 20, 2009, 5:11 AM
I will give you a simple example on this. I hope you will be able to get a very goo idea from this.
Let's say this is the file 'abc.xml'.
Now we are writing the code to deserialize this xml file.
[XmlRoot("MyFile")]
[Serializable]
public class MyFile
{
[XmlElement("Setting1")]
public string setting1;
[XmlElement("Setting2")]
public int setting2;
[XmlElement("Setting3")]
public bool setting3;
public static MyFile SelfRef
{
get
{
return selfref;
}
}
#region Constructor
static MyFile()
{
selfref = new MyFile();
Read();
}
#endregion
public static void Read()
{
try
{
XmlDocument document = new XmlDocument();
string filename = "abc.xml";
if (File.Exists(filename))
document.Load(filename);
else
return;
XmlSerializer xSerializer = new XmlSerializer(typeof(MyFile));
XmlNodeReader xNodeReader = new XmlNodeReader(document.DocumentElement);
selfref = (UserPreferences)xSerializer.Deserialize(xNodeReader);
}
catch (Exception ex)
{
}
}
}
public class Setting1
{
[XmlElement("name")]
public string name;
[XmlElement("type")]
public int type;
public Setting1()
{
}
}
If you have any problem, please do not hesitate to ask me.