我有一个扩展基类的程序,如下所示:
namespace ConsoleExample
{
[Serializable, XmlRoot("ServiceConfig")]
public class ServiceConfig : BaseConfig<ServiceConfig>
{
}
}
其中BaseConfig包含以下方法:
public abstract class BaseConfig<T> where T : BaseConfig<T>
{
...
public void LoadConfig()
{
// Load configuration file
ConfigReader<BaseConfig<T>> _configReader = new ConfigReader<BaseConfig<T>>(configFileName);
_configReader.Load();
...
和ConfigReader是:
public class ConfigReader<T>
{
...
public Boolean Load()
{
try
{
reader = new XmlTextReader(new StreamReader(_actualPath));
XmlSerializer serializer = new XmlSerializer(typeof(T));
deserializedObject = (T)(serializer.Deserialize(reader));
}
}
...
我的XML就像这样:
<?xml version="1.0" encoding="utf-8"?>
<ServiceConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<WindowTitle>Utility</WindowTitle>
<LicenseKey />
<BaseUri />
<!-- Database connection information -->
<DatabaseInfo>
<ServerName>ABC</ServerName>
<DatabaseName>XYZ</DatabaseName>
...
当我运行此程序时,我收到"<ServiceConfig xmlns=''> was not expected error
我发现这个post建议添加XMLRoot标记,但这没有帮助。我想这可能是因为反序列化是在BaseConfig程序中编码的,并且不知何故没有正确解释XMLRoot但不确定如何纠正。
修改
通过使用just(not BaseConfig)创建ConfigReader对象来解决这个问题:
public void LoadConfig()
{
// Load configuration file
ConfigReader<T> _configReader = new ConfigReader<T>(configFileName);
...