XML 反序列化不起作用
我需要将 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。请帮我解决它。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
识别此类问题的最佳方法是实际上反转序列化逻辑。
使用与 XML 中的数据相匹配的数据创建对象。然后尝试对其进行序列化,以便输出与您想要反序列化的数据相同。
这样,您实际上可以“查看”可应用于属性的可用属性的效果。
如果它序列化相同,您也可以反序列化它。
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.
失败是因为属性错误;区别在于
XmlArrayItem
需要两级关系 (...
);因此,对于Players
来说,它应该是:尽管就我个人而言,我更喜欢:(
即没有
set
,并且使用列表而不是数组),甚至是延迟实例化:
It fails because the attributes are wrong; the difference is that
XmlArrayItem
expects an two-level relationship (<Players><Players><Player .../>...</Players></Players>
); hence forPlayers
it should be:although personally, I'd prefer:
(i.e. no
set
, and a list instead of an array)or even the lazily-instantiated: