不可能从对象提取XML数据
本文关键字:XML 数据 提取 对象 不可能 | 更新日期: 2023-09-27 18:09:51
我有一个非常简单的应用程序,其中一个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();
}
有人能发现这个错误吗?
将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;
}
}
然后在你的main方法中你可以这样做:
static void Main(string[] args)
{
SettingSerializer serializer = new SettingSerializer();
Settings settings = serializer.Deserialize();
Console.WriteLine(settings.Homepage);
Console.WriteLine(settings.DefaultAudioLevel);
Console.ReadKey();
}
正如您最初所拥有的那样,正在反序列化的settings
与主方法中包含的settings
之间没有联系。您只需创建一个新对象并输出其默认值,在您的示例中是null
或空字符串。