I’m trying to deserialize the following XML document:
<?xml version="1.0" encoding="utf-8" ?>
<TestPrice>
<Price>
<A>A</A>
<B>B</B>
<C>C</C>
<Intervals>
<Interval>
<A>A</A>
<B>B</B>
<C>C</C>
</Interval>
<Interval>
<A>A</A>
<B>B</B>
<C>C</C>
</Interval>
</Intervals>
</Price>
</TestPrice>
And I have three classes defined to deserialize this into an object graph:
public class TestPrice
{
private List<Price> _prices = new List<Price>();
public List<Price> Price
{
get { return _prices; }
set { _prices = value; }
}
}
public class Price
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
private List<Interval> _intervals = new List<Interval>();
public List<Interval> Intervals
{
get { return _intervals; }
set { _intervals = value; }
}
}
public class Interval
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
I can deserialize each part ok. That is, I can do:
var serializer = new XmlSerializer(typeof(Price));
var priceEntity = ((Price)(serializer.Deserialize(XmlReader.Create(stringReader))));
And priceEntity is correctly initialized with the XML data contained in stringReader, including the List<Interval> Intervals. However if I try to deserialize a TestPrice instance, it always comes up with an empty List<Price> Price.
If I change the definition of TestPrice like this:
public class TestPrice
{
public Price Price { get; set; }
}
It works. but of course my XSD defines Price as a sequence. I have other entities deserializing just fine, but they don’t include sequences in the root element. Is there a limitation that I’m unaware of? Should I include some sort of metadata in TestPrice?
Just decorate your Price collection with
[XmlElement]:Also you seem to be deserializing
Price, whereas the root tag in your XML isTestPrice. So, here’s a full example: