我已经设法从几个类轻松生成 XML 文件,如下所示;
public class AllConfig : XMLEncapsulator
{
[XmlElement("Database-Settings")]
public DataBaseConfiguration databaseConfiguration { get; set; }
[XmlElement("Merlin-Settings")]
public MerlinConfiguration merlinConfiguration { get; set; }
}
public class DataBaseConfiguration : XMLEncapsulator
{
public string dbIP { get; set; }
public int ?port { get; set; }
public string username { get; set; }
public string password { get; set; }
}
public class MerlinConfiguration : XMLEncapsulator
{
public string MerlinIP { get; set; }
public int ?MerlinPort { get; set; }
public int ?RecievingPort { get; set; }
}
// load classes with information, then;
try
{
allConfig.databaseConfiguration = dbConfig;
allConfig.merlinConfiguration = merlinConfig;
allConfig.Save();
}
catch (Exception ErrorFinalisingSave)
{
MessageBox.Show(ErrorFinalisingSave.Message + "3");
}
这完美地工作并给了我:
<AllConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<databaseConfiguration>
<dbIP></dbIP>
<port></port>
<username></username>
<password></password>
</databaseConfiguration>
<merlinConfiguration>
<MerlinIP></MerlinIP>
<MerlinPort></MerlinPort>
<RecievingPort></RecievingPort>
</merlinConfiguration>
</AllConfig>
但是,我该如何将其重新检索到我的表单中?所以我有这样的东西,但我似乎无法让它工作;
AllConfig allConfig;
DataBaseConfiguration dbConfig;
MerlinConfiguration merlinConfig;
//need to load here.
//check if values loaded are null, and then load them if they exist into textboxes and such.
我应该加载两个配置类,然后将它们分配给整个配置类吗?还是我需要加载整个类并为此分配子配置类,就像这样;
allConfig = new AllConfig();
dbConfig = new DataBaseConfiguration();
merlinConfig = new MerlinConfiguration();
allConfig.databaseConfiguration = dbConfig;
allConfig.merlinConfiguration = merlinConfig;
allConfig.databaseConfiguration.Load();
allConfig.merlinConfiguration.Load();
编辑:这是我的加载方法;
public virtual void Load()
{
if (File.Exists(DeviceManager.path))
{
StreamReader sr = new StreamReader(DeviceManager.path);
XmlTextReader xr = new XmlTextReader(sr);
XmlSerializer xs = new XmlSerializer(this.GetType());
object c;
if (xs.CanDeserialize(xr))
{
c = xs.Deserialize(xr);
Type t = this.GetType();
PropertyInfo[] properties = t.GetProperties();
foreach (PropertyInfo p in properties)
{
p.SetValue(this, p.GetValue(c, null), null);
}
}
xr.Close();
sr.Close();
}
}