XML反序列化不起作用
本文关键字:不起作用 反序列化 XML | 更新日期: 2023-09-27 18:23:47
我需要将XML文件反序列化为对象。XML内容:
<Players dealerId="2">
<Player id="1">
<ScreenName>JetYeo</ScreenName>
</Player>
<Player id="2">
<ScreenName>Test</ScreenName>
</Player>
</Players>
我定义了一个对象类:
[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; }
}
但是,反序列化不起作用:Players数组为null。请帮我解决。谢谢。
识别这类问题的最佳方法是实际反转序列化逻辑。使用与XML中的数据匹配的数据创建对象。然后尝试序列化它,使输出与您想要反序列化的数据相同。
通过这种方式,您实际上可以"看到"可应用于属性的可用属性的效果。
如果它序列化了相同的内容,您也可以反序列化它。
由于属性错误而失败;不同之处在于CCD_ 1期望两级关系(<Players><Players><Player .../>...</Players></Players>
);因此,对于Players
,它应该是:
[XmlElement("Player")]
public Player[] Players { get; set; }
尽管就我个人而言,我更喜欢
private readonly List<Player> players = new List<Player>();
[XmlElement("Player")]
public List<Player> Players { get { return players; } }
(即没有set
,使用列表而不是数组)
甚至是懒惰实例化的:
private List<Player> players;
[XmlElement("Player")]
public List<Player> Players {
get { return players ?? (players = new List<Player>()); }
}