在 XmlSerializer 上使用 Deserialize 时始终为空

iKo*_*ode 1 .net c# asp.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>
Run Code Online (Sandbox Code Playgroud)

我的代码:

       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);
Run Code Online (Sandbox Code Playgroud)

我的课:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ves 5

将一个添加XmlElementAttribtue到您的课程中:

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

旁注:为了帮助调试此类内容,请尝试填充您的类,对其进行序列化,然后查看 XML 的结构是什么样的。然后您可以调整您的类,直到生成的 XML 看起来像您想要反序列化的内容。