如何反序列化一个XML数组包含多种类型的元素在C# [英] How to deserialize an XML array containing multiple types of elements in C#
问题描述
我试图反序列化以下文件:
I'm trying to deserialize the following file:
<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);
}
}
}
}
'm希望得到一个联赛对象包含一个Skaters列表3元素和一个目标列表2元素。我得到预期的Skaters列表,但Goalies列表是空的。我做错了什么?
I'm expecting to get back a League object containing a Skaters list with 3 elements and a Goalies list with 2 elements. I do get the expected Skaters list but the Goalies list is empty. What am I doing wrong?
推荐答案
有两种方法:第一个是做类似的操作:
There are two ways to do this; the first is to do something like:
[XmlArray("players")]
[XmlArrayItem("skater", Type=typeof(Skater))]
[XmlArrayItem("goalie", Type=typeof(Goalie))]
public List<SomeCommonBaseClass> Players { get; set; }
将两个元素类型映射到单个集合中。最差情况下, SomeCommonBaseClass
可以是对象
:
which maps the two element types inside a single collection. Worst case, SomeCommonBaseClass
could be object
:
[XmlArray("players")]
[XmlArrayItem("skater", Type=typeof(Skater))]
[XmlArrayItem("goalie", Type=typeof(Goalie))]
public List<object> Players { get; set; }
第二个是使< players>
映射到包装器对象:
The second is to make <players>
map to a wrapper object:
[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;}
}
哪一个取决于情况;后者允许诸如至多一个守门员之类的东西改变为:
Which to choose depends on the circumstance; the latter allows things like "at most one goalie", by changing it to:
[XmlElement("goalie")]
public Goalie Goalie {get;set;}
这篇关于如何反序列化一个XML数组包含多种类型的元素在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!