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

标签 c# xml serialization

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

相关文章:

c# - 仅允许 TLS 1.0 后仍然可以进行 TLS 1.2 握手

java - 将 xml 转换为另一个 xml 的最简单方法是什么?

c# - JsonConvert.DeserializeObject 的 JSON.net 问题

c# - SpeechSynthesizer.SpeakAsync 方法不会立即说话

c# - 防止在 Visual Studio 安装程序项目中自动添加依赖项

python - XML验证错误: Char 0x0 out of allowed range.

c# - 在没有单独方法的情况下在 RESTful WCF 中混合 XML 和 JSON

java - 使Jackson在序列化时不输出类名(使用Spring MVC)

c# - 将 JSON 反序列化为字符串

javascript - Ajax调用 Controller 后抛出错误