gpt4 book ai didi

c# - 如何在 C# 中反序列化包含多种类型元素的 XML 数组

转载 作者:可可西里 更新时间:2023-11-01 08:19:08 26 4
gpt4 key购买 nike

我正在尝试反序列化以下文件:

<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);
}
}
}
}

我希望得到一个 League 对象,其中包含一个包含 3 个元素的 Skaters 列表和一个包含 2 个元素的 Goalies 列表。我确实得到了预期的溜冰者名单,但守门员名单是空的。我做错了什么?

最佳答案

有两种方法可以做到这一点;第一种是做类似的事情:

[XmlArray("players")]
[XmlArrayItem("skater", Type=typeof(Skater))]
[XmlArrayItem("goalie", Type=typeof(Goalie))]
public List<SomeCommonBaseClass> Players { get; set; }

将两种元素类型映射到一个集合中。最坏的情况,SomeCommonBaseClass可能是 object :

[XmlArray("players")]
[XmlArrayItem("skater", Type=typeof(Skater))]
[XmlArrayItem("goalie", Type=typeof(Goalie))]
public List<object> Players { get; set; }

第二个是制作<players>映射到包装器对象:

[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;}

关于c# - 如何在 C# 中反序列化包含多种类型元素的 XML 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20133007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com