Often, data structures are not strictly hierarchical. For instance, consider a team consisting of players, and marking one of those players as captain:
If I would serialize an instance of this model to XML, I would expect some structure like:
this.CreateGraphics()
That is, the aggregation is serialized as nested elements and the directed association is serialized with the reference to an id.
I would like to achieve this from C# code without having to write custom XML serializers, preferably just by adding an attribute, something like:
using
Does anything like this exist? I had a look at XML schema's but it doesn't seem to provide what I need here.
Bonus: It would be even better if I could generate the intermediate C# code, with the appropriate attributes set, directly from the UML - or any other modeling formalism for that matter. In the end, I just want to be able to specify the type of association on a high abstraction level and have the XML serialization conform to that, with the least amount of effort / room for mistakes.
答案 0 :(得分:0)
首先,我不知道你想要的任何XML格式。我不是专家,只使用XML进行序列化/反序列化。不过,我可能会为您提供可行的解决方案。 您可以在MSDN
上找到大量信息如果您有架构文件,则可以使用XSD创建类。 我通常会反过来创建类,然后为它创建一个模式来验证我收到的数据。
我会在玩家身上使用一个属性来判断谁是队长,因此团队中的属性只返回拥有IsCaptain == true的玩家
class Team
{
public List<Player> Players { get; set; }
public Player Captain { get { return Players.Find(p => p.IsCaptain); } }
}
class Player
{
public string ID { get; set; }
public bool IsCaptain { get; set; }
}
或者只是将队列ID中的ID存储在Team上以进行序列化和反序列化,并在xml序列化中忽略属性Player Captain。
class Team
{
public List<Player> Players { get; set; }
public string CaptainID { get; set; }
[NonSerialized]
[System.Xml.Serialization.XmlIgnore]
public Player Captain { get { return Players.Find(p => p.ID == CaptainID); } }
}