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

时间:2012-06-20 15:25:52

标签: c# asp.net .net deserialization

我想反序列化一些看起来像这样的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>

我的代码:

       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);

我的班级:

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; }

    }
}

2 个答案:

答案 0 :(得分:4)

在您的班级中添加XmlElementAttribtue

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

旁注:为了帮助调试这样的东西,请尝试填充类,序列化它,然后查看XML的结构。然后,您可以调整您的类,直到生成的XML看起来像您要反序列化的那样。

答案 1 :(得分:1)

问题是,该解串器不使用list&lt;&gt;的SET方法。属性,但它通过GET方法,然后为每个项目调用ADD。这意味着,必须通过ctor初始化物业预订。

c# System.Xml.Serialization does not goes throught set method of Public List<T>