I need to deserialize a XML file to a object. The XML contents:
<Players dealerId="2">
<Player id="1">
<ScreenName>JetYeo</ScreenName>
</Player>
<Player id="2">
<ScreenName>Test</ScreenName>
</Player>
</Players>
I define a object class:
[Serializable()]
[XmlRoot("Players")]
public class Players
{
[XmlAttribute("dealerId")]
public int DealerId { get; set; }
[XmlArrayItem("Player", typeof(Player))]
public Player[] Players { get; set; }
}
[Serializable()]
[XmlRoot("Player")]
public class Player
{
[XmlAttribute("id")]
public int Id { get; set; }
[XmlElement("ScreenName")]
public string ScreenName { get; set; }
}
However, deserialization does not work: Players array is null. Please help me to solve it. Thanks.
It fails because the attributes are wrong; the difference is that
XmlArrayItemexpects an two-level relationship (<Players><Players><Player .../>...</Players></Players>); hence forPlayersit should be:although personally, I’d prefer:
(i.e. no
set, and a list instead of an array)or even the lazily-instantiated: