Tag: XmlSerializer
public class Person { public string Name { get; set; } }
public class Player :Person { public string Position { get; set; } }
public class Coach :Person { public string Type { get; set; } }
public class Team { public Team() { Persons = new List<Person>(); } [XmlArrayItem(typeof(Player))] [XmlArrayItem(typeof(Coach))] public List<Person> Persons { get; set; } [XmlElement(typeof(Player))] [XmlElement(typeof(Coach))] public Person MainPerson { get; set; } }
Team team = new Team(); team.Persons.Add(new Player() { Name = "小野伸二", Position = "MF" }); Player kagawa = new Player() { Name = "香川真司", Position = "FW" }; team.Persons.Add(kagawa); team.Persons.Add(new Coach() { Name = "ジーコ", Type = "自由" }); team.MainPerson = kagawa; XmlSerializer serializer = new XmlSerializer(typeof(Team)); FileStream fs = new FileStream("c:/temp/test.xml", FileMode.Create); serializer.Serialize(fs, team); fs.Close();
<?xml version="1.0"?> <Team xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Persons> <Player> <Name>小野伸二</Name> <Position>MF</Position> </Player> <Player> <Name>香川真司</Name> <Position>FW</Position> </Player> <Coach> <Name>ジーコ</Name> <Type>自由</Type> </Coach> </Persons> <Player> <Name>香川真司</Name> <Position>FW</Position> </Player> </Team>