简体   繁体   English

在XmlSerializer上使用反序列化时始终为空

[英]Always empty when using Deserialize on XmlSerializer

I want to deserialize some XML that looks like this: 我想反序列化一些看起来像这样的XML:

XML: XML:

     <bookings>
        <booking>
           <timeStart>2012/7/2 11:00:00</timeStart>
           <timeEnd>2012/7/2 12:00:00</timeEnd>
        </booking>
        <booking>
            <timeStart>2012/7/10 08:30:00</timeStart>
            <timeEnd>2012/7/10 10:30:00</timeEnd>
        </booking>         
     </bookings>

My code: 我的代码:

       var calUrlStr = "http://xxx.com?action=xxxxxx?x=1&y=2";

       HttpWebRequest webRequest = GetWebRequest(calUrlStr);
       HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

       XmlRootAttribute xRoot = new XmlRootAttribute();
       xRoot.ElementName = "bookings";
       xRoot.IsNullable = true;

       XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyDomain.GCalBooking.GCalBookings), xRoot);

       Stream theStream = response.GetResponseStream();
       StreamReader reader = new StreamReader(theStream);

       MyDomain.GCalBooking.GCalBookings rateResponse = (MyDomain.GCalBooking.GCalBookings)xmlSerializer.Deserialize(reader);

My Class: 我的课:

namespace MyDomain.GCalBooking
{
    public class GCalBookings
    {

        public virtual List<Booking> Bookings { get; set; }


    }

    public class Booking
    {

        public string timeStart { get; set; }
        public string timeEnd { get; set; }

    }
}

Add an XmlElementAttribtue to your class: XmlElementAttribtue添加到您的类中:

public class GCalBookings
{
    [XmlElement("booking")]
    public virtual List<Booking> Bookings { get; set; }
}

Side note: To help debug stuff like this, try populating your class, serializing it, and then look at what the structure of the XML looks like. 旁注:为了帮助调试此类内容,请尝试填充您的类,对其进行序列化,然后查看XML的结构。 Then you can tweak your class until the resulting XML looks like what you want to deserialize. 然后,您可以调整类,直到生成的XML看起来像您要反序列化的XML。

problem is, that deserializer don't use a SET method of list<> property, but it goes through GET method and then calls ADD for each item. 问题是,解串器不使用list <>属性的SET方法,而是通过GET方法,然后为每个项目调用ADD。 It means, that property Bookings must be initialzied via ctor. 这意味着,必须通过ctor初始化物业预订。

see c# System.Xml.Serialization does not goes throught set method of Public List<T> 请参见c#System.Xml.Serialization没有通过Public List <T>的set方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM