C# · 12月 23, 2021

c# – 反序列化对象列表的问题

我无法反序列化对象列表.我只能获得一个对象序列化到一个对象但无法获取列表.我没有得到错误它只返回一个空列表.这是返回的 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);