c# – 反序列化对象列表的问题
发布时间:2020-12-15 04:27:21 所属栏目:百科 来源:网络整理
导读:我无法反序列化对象列表.我只能获得一个对象序列化到一个对象但无法获取列表.我没有得到错误它只返回一个空列表.这是返回的 XML: locations location locationtype="building" locationtypeid="1" id1/id nameBuilding Name/name descriptionDescription of
我无法反序列化对象列表.我只能获得一个对象序列化到一个对象但无法获取列表.我没有得到错误它只返回一个空列表.这是返回的
XML:
<locations> <location locationtype="building" locationtypeid="1"> <id>1</id> <name>Building Name</name> <description>Description of Building</description> </location> </locations> 这是我的类,我在GetAll方法中反序列化: [Serializable()] [XmlRoot("location")] public class Building { private string method; [XmlElement("id")] public int LocationID { get; set; } [XmlElement("name")] public string Name { get; set; } [XmlElement("description")] public string Description { get; set; } [XmlElement("mubuildingid")] public string MUBuildingID { get; set; } public List<Building> GetAll() { var listBuildings = new List<Building>(); var building = new Building(); var request = WebRequest.Create(method) as HttpWebRequest; var response = request.GetResponse() as HttpWebResponse; var streamReader = new StreamReader(response.GetResponseStream()); TextReader reader = streamReader; var serializer = new XmlSerializer(typeof(List<Building>),new XmlRootAttribute() { ElementName = "locations" }); listBuildings = (List<Building>)serializer.Deserialize(reader); return listBuildings; } } 解决方法
试试这个:
[XmlRoot("locations")] public class BuildingList { public BuildingList() {Items = new List<Building>();} [XmlElement("location")] public List<Building> Items {get;set;} } 然后反序列化整个BuildingList对象. var xmlSerializer = new XmlSerializer(typeof(BuildingList)); var list = (BuildingList)xmlSerializer.Deserialize(xml); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |