2012-06-20 28 views
1

使用反序列化時總是空的我想反序列化一些XML,看起來像這樣:上的XmlSerializer

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

    } 
} 

回答

4

添加XmlElementAttribtue到類:

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

邊注:爲了幫助調試這樣的東西,儘量填充類,序列化,然後再看一下XML的結構看起來像。然後你可以調整你的類,直到生成的XML看起來像你想要反序列化的東西。