gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 01:49:47 28 4
gpt4 key购买 nike

我在反序列化对象列表时遇到问题。我只能将一个对象序列化为一个对象,但无法获取列表。我没有收到任何错误,它只是返回一个空列表。这是返回的 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);

关于c# - 反序列化对象列表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18367168/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com