public class PersistableObject
{
public static T Load<T>(string fileName) where T : PersistableObject, new()
{
T result = default(T);
using (XmlReader reader = XmlReader.Create(fileName))
{
result = new XmlSerializer(typeof(T)).Deserialize(reader) as T;
}
return result;
}
public void Save<T>(string fileName) where T : PersistableObject
{
using (FileStream stream = new FileStream(fileName, FileMode.CreateNew))
{
new XmlSerializer(typeof(T)).Serialize(stream, this);
}
}
}
public class DatabaseConfiguration : PersistableObject
{
public string Host { get; set; }
public string Schema { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
我使用以下代码加载XML:
var configuration = PersistableObject.Load<DatabaseConfiguration>("Database.xml");
但是,配置的属性为null。这是Database.xml:
<?xml version="1.0"?>
<DatabaseConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
<Host>localhost</Host>
<Schema>chromium</Schema>
<Username>root</Username>
<Password></Password>
</DatabaseConfiguration>
由于某种原因,它们保持为空,并且未分配任何内容。为什么?
答案 0 :(得分:3)
您的Database.xml
内容不正确,特别是关闭DatabaseConfiguration
元素的第二行。
将其替换为:
<?xml version="1.0"?>
<DatabaseConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<Host>localhost</Host>
<Schema>chromium</Schema>
<Username>root</Username>
<Password></Password>
</DatabaseConfiguration>