当我尝试在XML下面反序列化时,我收到错误:设置xmlns =''不是预期的。 我已在下面的类中映射了根节点,为什么我会收到该错误?
我的xml:
<Settings>
<Access>
<Phone hasTextField="true">
<Item description="CMS" />
</Phone>
</Access>
</Settings>
类 Settings.cs:
[XmlRoot("Settings")]
public class AccessNodes
{
[XmlElement("Access")]
public Access AccessList { get; set; }
}
[XmlType("Access")]
public class Access
{
[XmlElement("Phone")]
public AccessItem Phone { get; set; }
}
public class AccessItem
{
public AccessItem()
{
Items = new List<Item>();
}
[XmlAttribute("hasTextField")]
public bool HasTextField { get; set; }
[XmlElement("Item")]
public List<Item> Items { get; set; }
}
[XmlType("Item")]
public class Item
{
[XmlAttribute("description")]
public string Description { get; set; }
}
SettingsReader.cs
public static class SettingsReader<T>
{
public static T Deserialize(string basePath)
{
string filename = basePath + ".xml";
T t = default(T);
XmlSerializer xs = new XmlSerializer(typeof(T));
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
t = (T)xs.Deserialize(fs);
}
return t;
}
调用SettingsReader.cs
Access access = SettingsReader<Access>.Deserialize(Server.MapPath("~/App_Data/access"));
答案 0 :(得分:1)
您正在尝试反序列化错误的元素 - 您尝试反序列化Access
类型,而您的顶级节点是Settings
,这是应用于AccessNodes
的名称类型。
请改为尝试:
AccessNodes settings = SettingsReader<AccessNodes>.Deserialize(...);