[英]XML Deserialization doesn't work
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; }
}
I load the XML using the following code: 我使用以下代码加载XML:
var configuration = PersistableObject.Load<DatabaseConfiguration>("Database.xml");
However, configuration's properties are null. 但是,配置的属性为null。 This is Database.xml: 这是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>
They stay null for some reason and are not assigned anything. 由于某种原因,它们保持为空,并且没有分配任何东西。 Why's that? 为什么?
Your Database.xml
content is incorrect, specifically its second line that closes the DatabaseConfiguration
element. 您的Database.xml
内容不正确,特别是它的第二行关闭了DatabaseConfiguration
元素。
Replace it with: 替换为:
<?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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.