I have a very simple application, where a XML file is de-serialized into objects. When I try to read out the values from the object I get null
.
My XML-file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
<HomePage>http://www.google.dk</HomePage>
<DefaultAudioLevel>100</DefaultAudioLevel>
</Settings>
And my model looks like this:
[Serializable()]
public class Settings
{
[XmlElement("HomePage")]
public string Homepage { get; set; }
[XmlElement("DefaultAudioLevel")]
public string DefaultAudioLevel { get; set; }
}
And the SettingSerializer.cs
:
public class SettingSerializer
{
private string path;
private string EXE = Assembly.GetExecutingAssembly().GetName().Name;
Settings settings = null;
public SettingSerializer(string xmlPath = null)
{
path = new FileInfo(xmlPath ?? EXE + ".xml").FullName.ToString();
}
public void Deserialize()
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
StreamReader reader = new StreamReader(path);
settings = (Settings)serializer.Deserialize(reader);
reader.Close();
}
}
And my test class:
static void Main(string[] args)
{
SettingSerializer serializer = new SettingSerializer();
serializer.Deserialize();
Settings settings = new Settings();
Console.WriteLine(settings.Homepage);
Console.WriteLine(settings.DefaultAudioLevel);
Console.ReadKey();
}
Can anybody spot the error?
Change your Serializer
to this:
public class SettingSerializer
{
private string path;
private string EXE = Assembly.GetExecutingAssembly().GetName().Name;
public SettingSerializer(string xmlPath = null)
{
path = new FileInfo(xmlPath ?? EXE + ".xml").FullName.ToString();
}
public Settings Deserialize()
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
StreamReader reader = new StreamReader(path);
var settings = (Settings)serializer.Deserialize(reader);
reader.Close();
return settings;
}
}
Then in your main method you can do this:
static void Main(string[] args)
{
SettingSerializer serializer = new SettingSerializer();
Settings settings = serializer.Deserialize();
Console.WriteLine(settings.Homepage);
Console.WriteLine(settings.DefaultAudioLevel);
Console.ReadKey();
}
As you had it originally, there is no connection between the settings
that was being deserialized and the settings
that was contained in the main method. You just create a new object and print out whatever its default values are, which in your case are null
or empty strings.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.