Leo Vo
Leo Vo

Reputation: 10330

XML deserialization does not work

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.

Upvotes: 0

Views: 5002

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062780

It fails because the attributes are wrong; the difference is that XmlArrayItem expects an two-level relationship (<Players><Players><Player .../>...</Players></Players>); hence for Players it should be:

[XmlElement("Player")]
public Player[] Players { get; set; }

although personally, I'd prefer:

private readonly List<Player> players = new List<Player>();
[XmlElement("Player")]
public List<Player> Players { get { return players; } }

(i.e. no set, and a list instead of an array)

or even the lazily-instantiated:

private List<Player> players;
[XmlElement("Player")]
public List<Player> Players {
    get { return players ?? (players = new List<Player>()); }
}

Upvotes: 3

Myrtle
Myrtle

Reputation: 5831

The best way to identify this kind of problems is to actually reverse your serialization logic. Create the object with the data that matches the data you have in your XML. Then try to serialize it so that the output is the same as the data you would like to deserialize.

This way, you can actually 'see' the effect of the available attributes that you can apply on the properties.

If it serializes the same, you can also deserialize it.

Upvotes: 7

Related Questions