我有一个非常简单的应用程序,其中XML文件被反序列化为对象。当我尝试从对象中读出值时,我得到null
。
我的XML文件如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
<HomePage>http://www.google.dk</HomePage>
<DefaultAudioLevel>100</DefaultAudioLevel>
</Settings>
我的模型看起来像这样:
[Serializable()]
public class Settings
{
[XmlElement("HomePage")]
public string Homepage { get; set; }
[XmlElement("DefaultAudioLevel")]
public string DefaultAudioLevel { get; set; }
}
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();
}
}
我的测试班:
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();
}
有人能发现错误吗?
答案 0 :(得分:1)
将您的Serializer
更改为:
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;
}
}
然后在你的主要方法中你可以这样做:
static void Main(string[] args)
{
SettingSerializer serializer = new SettingSerializer();
Settings settings = serializer.Deserialize();
Console.WriteLine(settings.Homepage);
Console.WriteLine(settings.DefaultAudioLevel);
Console.ReadKey();
}
正如您最初所做的那样,正在反序列化的settings
与main方法中包含的settings
之间没有任何关联。您只需创建一个新对象并打印出其默认值,在您的情况下为null
或空字符串。