应该是容易的xml反序列化
本文关键字:xml 反序列化 | 更新日期: 2023-09-27 18:00:55
我不知道我做错了什么,但每次我试图反序列化我的xml对象时,所有的值都会为null。我知道路径是正确的,代码正在正确地加载文档,但当我尝试反序列化它时,一切都是空的。有人能告诉我我在这里做错了什么吗?
我的xml结构:
<settings>
<settingsList>
<setting>
<name>ConnectionString</name>
<value>testconnectionstring</value>
</setting>
</settingsList>
</settings>
设置:
[DataContract]
[Serializable()]
[XmlRoot(ElementName = "settings")]
public class Settings
{
[DataMember]
[XmlElement("settingsList")]
public List<Setting> SettingsList { get; set; }
}
设置.cs:
[DataContract]
[Serializable()]
[XmlRoot(ElementName = "setting")]
public class Setting
{
[DataMember]
[XmlElement("name")]
public string Name { get; set; }
[DataMember]
[XmlElement("value")]
public string Value { get; set; }
}
最后,我的反序列化代码:
var xml = XDocument.Load(docPath);
var serializer = new XmlSerializer(typeof(Settings));
var settings = (Settings)serializer.Deserialize(xml.CreateReader());
您需要使用XmlArray和XmlArrayItem:
[DataMember]
[XmlArray("settingsList")]
[XmlArrayItem("setting")]
public List<Setting> SettingsList { get; set; }
我想问题就在这里:setting.cs中的[XmlRoot(ElementName = "setting")]
。我认为它一定是[XmlRoot(ElementName = "settingList")]
,因为setting list是所有设置的父级。试试看。