我试图反序列化以下文件:
<league> <players> <skater> <name>Wayne Stamkos</name> <goals>23</goals> <assists>34</assists> </skater> <skater> <name>Sidney Lindros</name> <goals>41</goals> <assists>44</assists> </skater> <goalie> <name>Martin Roy</name> <wins>15</wins> <losses>12</losses> </goalie> <skater> <name>Paul Forsberg</name> <goals>21</goals> <assists>51</assists> </skater> <goalie> <name>Roberto Rinne</name> <wins>18</wins> <losses>23</losses> </goalie> </players> </league>
使用以下代码:
namespace ConsoleApplication2 { [XmlRoot("league")] public class League { [XmlArray("players")] [XmlArrayItem("skater")] public List<Skater> skaters { get; set; } [XmlArrayItem("goalie")] public List<Goalie> goalies { get; set; } } public class Skater { [XmlElement("name")] public string Name; [XmlElement("goals")] public int Goals; [XmlElement("assists")] public int Assists; } public class Goalie { [XmlElement("name")] public string Name; [XmlElement("wins")] public int Wins; [XmlElement("losses")] public int Losses; } class Program { static void Main(string[] args) { using (FileStream reader = new FileStream(@"C:\Temp\test.xml",FileMode.Open,FileAccess.Read)) { var ser = new XmlSerializer(typeof(League)); League league = (League)ser.Deserialize(reader); } } } }
我期待得到一个包含一个包含3个元素和一个具有2个元素的Goalies列表的Skaters列表的League对象.我得到预期的Skaters列表,但Goalies列表是空的.我究竟做错了什么?
解决方法
有两种方法可以做到这一点:第一个是做一些像:
[XmlArray("players")] [XmlArrayItem("skater",Type=typeof(Skater))] [XmlArrayItem("goalie",Type=typeof(Goalie))] public List<SomeCommonBaseClass> Players { get; set; }
它将两个元素类型映射到单个集合中.最差的情况下,SomeCommonBaseClass可以是对象:
[XmlArray("players")] [XmlArrayItem("skater",Type=typeof(Goalie))] public List<object> Players { get; set; }
第二个是使<玩家>映射到包装器对象:
[XmlElement("players")] public Players Players { get;set;} ... public class Players { [XmlElement("skater")] public List<Skater> Skaters {get;set;} [XmlElement("goalie")] public List<Goalie> Goalies {get;set;} }
哪种选择取决于情况;后者允许像“至多一个守门员”一样,将其改为:
[XmlElement("goalie")] public Goalie Goalie {get;set;}