问题
I want to deserialize some XML that looks like this:
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; }
}
}
回答1:
Add an XmlElementAttribtue to your class:
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. Then you can tweak your class until the resulting XML looks like what you want to deserialize.
回答2:
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. It means, that property Bookings must be initialzied via ctor.
see c# System.Xml.Serialization does not goes throught set method of Public List<T>
来源:https://stackoverflow.com/questions/11122870/always-empty-when-using-deserialize-on-xmlserializer